Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

第 9 期(2019-05-16):CSS兼容性验证 #11

Copy link
Copy link
@wingmeng

Description

@wingmeng
Issue body actions

类型:常用技巧
难度:★★☆

封装一个特性检测函数,用以验证当前浏览器是否支持某个 CSS 属性

注:需要兼容 IE8+(含)以及其他主流浏览器

/**
 * @param {string} [prop] - 需要验证的 CSS 属性名。
 * @return:
      1. 当 `prop` 为字符串时,返回当前浏览器是否支持该 CSS 属性的布尔值
      2. 当 `prop` 为空时,返回一个由当前浏览器支持的所有 CSS 属性名组成的数组
 */
function supported(prop) {
  // 你的代码
}

测试用例: (以下结果来自 Chrome 74)

supported('animation');  // true
supported('background-clip');  // true
supported('mix-blend-mode');  // true
supported('-webkit-user-drag');  // true
supported('-moz-force-broken-image-icon');  // false
supported('-ms-block-progression');  // false
supported('abcd');  // false
supported();  // ["align-content", "align-items", "align-self" ... ]

参考答案:

function supported(prop) {
  var result = [];
  var format = function(p) {
    // 浏览器前缀处理
    var prefix = /^([webkit|moz|ms|o]+)[A-Z]+.*/.test(p) ? '-' : '';
    return prefix + p.replace(/[A-Z]/g, '-$&').toLowerCase();
  };

  if (Object.hasOwnProperty('keys') && Object.keys(document.body.style).length) {
    result = Object.keys(document.body.style).map(format);        
  } else {
    for (var key in document.body.style) {
      result.push(format(key));
    }
  }

  // 兼容 IE8
  if (!('indexOf' in Array.prototype)) {
    result = String(result);
  }

  if (typeof prop === 'undefined') {
    return typeof result === 'string' ? result.split(',') : result;
  }

  return result.indexOf(prop) === -1 ? false : true;
}

本期优秀回答者: 无 [哭笑.jpg]

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      Morty Proxy This is a proxified and sanitized view of the page, visit original site.