首页 > 技术文章 > CSS 模块的侦测

ziyoublog 2018-11-06 14:10 原文

CSS 的规格发展太快,新的模块层出不穷。不同浏览器的不同版本,对 CSS 模块的支持情况都不一样。有时候,需要知道当前浏览器是否支持某个模块,这就叫做“CSS模块的侦测”。

一个比较普遍适用的方法是,判断元素的style对象的某个属性值是否为字符串。

typeof element.style.animationName === 'string';
typeof element.style.transform === 'string';

如果该 CSS 属性确实存在,会返回一个字符串。即使该属性实际上并未设置,也会返回一个空字符串。如果该属性不存在,则会返回undefined

document.body.style['maxWidth'] // ""
document.body.style['maximumWidth'] // undefined

上面代码说明,这个浏览器支持max-width属性,但是不支持maximum-width属性。

注意,不管 CSS 属性名的写法带不带连词线,style属性上都能反映出该属性是否存在。

document.body.style['backgroundColor'] // ""
document.body.style['background-color'] // ""

另外,使用的时候,需要把不同浏览器的 CSS 前缀也考虑进去。

var content = document.getElementById('content');
typeof content.style['webkitAnimation'] === 'string'

这种侦测方法可以写成一个函数。

function isPropertySupported(property) {
  if (property in document.body.style) return true;
  var prefixes = ['Moz', 'Webkit', 'O', 'ms', 'Khtml'];
  var prefProperty = property.charAt(0).toUpperCase() + property.substr(1);

  for(var i = 0; i < prefixes.length; i++){
    if((prefixes[i] + prefProperty) in document.body.style) return true;
  }

  return false;
}

isPropertySupported('background-clip')
// true

 

推荐阅读