JS检测CSS属性浏览器是否支持的多种方法

这篇文章发布于 2019年11月8日,星期五,01:09,归类于 JS实例。 阅读 22132 次, 今日 9 次 6 条评论

 

一、原生CSS.supports语法

方法总是有的

返回布尔值true或者false,用来检测是否支持某CSS属性。

语法

CSS.supports(propertyName, value);
CSS.supports(supportCondition);

参数

propertyName
字符串。用来检测的CSS属性名。
value
字符串。用来检测的CSS属性值。
supportCondition
字符串。用来检测的CSS声明、表达式或者语法。

案例

例如,检测浏览器是否支持CSS filter滤镜,则可以:

result = CSS.supports('filter', 'blur(5px)');
result = CSS.supports('filter: 5px');   // 错误语法,返回false

例如在Chrome浏览器下返回:

CSS.supports滤镜支持检测

CSS.supports()还可以用来检测表达式,例如CSS变量语法:

result = CSS.supports('--username: zhangxinxu');
result = CSS.supports('(--username: zhangxinxu)');

结果如下图所示:

CSS.supports检测CSS变量

可以看到有没有括号都支持。

CSS.supports()还支持@supports规则,支持逻辑表达,例如:

result = CSS.supports('width: fit-content or width: -webkit-fit-content');
result = CSS.supports('(width: fit-content) or (width: -webkit-fit-content)');

第一行(粉色文字)返回false,第二行支持返回true(见下图)。可见,在这个语法环境下,括号是必须的:

逻辑规则语句支持测试

兼容性

和CSS @supports规则兼容性一样,Edge12+支持。

CSS 支持 API兼容性

尴尬的现状

实际开发的时候,需要使用到对CSS检测场景,往往都是针对低版本的IE浏览器,例如IE9-IE11。

于是尴尬的事情出现了,低版本的IE浏览器并不支持浏览器原生支持的CSS.supports()方法,于是,我们的实际需求并没有因为这个新的API而得到解决,不得不求助于其他方法。

二、JS赋值再取值的检测方法

这是我在实际项目中经常使用的一种方法,原理很简单,当浏览器不支持某个CSS属性的时候,就算你强制设置,获取的计算值也不会是你设置的属性值,还是检测浏览器是否支持CSS filter滤镜的例子。

我会这么处理:

document.head.style.filter = 'blur(5px)';
result = window.getComputedStyle(document.head).filter == 'blur(5px)';

我们看下上面代码在实际浏览器中的表现,首先是支持的Chrome浏览器,result的值是true

Chrome浏览器下截图

然后是不支持的IE11浏览器,result的值是false

IE11下的截图

此方法原理很简单,兼容性也非常好,实现的关键点就是使用getComputedStyle这个IE9+支持的DOM API方法,不能使用dom.style.xxxx直接获取。

如果是想要实现类似or或者and逻辑,例如带私有前缀那种,可以下面这样处理,正则匹配关键的部分:

document.head.style.width= 'fit-content';
document.head.style.width= '-moz-fit-content';
result = /fit-content/.test(window.getComputedStyle(document.head).width);

例如Firefox浏览器下的结果:

Firefox浏览器下截图

兼容性

IE9+

注意点

getComputedStyle()方法返回的是计算值,很多时候和设置的属性值并不同。

例如设置行高为小数,在IE浏览器下返回就是px计算值。

又或者设置background属性值,结果返回的是background兄弟姐妹一大家子值:

document.head.style.background = 'paint(abc)';
result = /paint/.test(window.getComputedStyle(document.head).background);
// reseult值是true
window.getComputedStyle(document.head).background
// "rgba(0, 0, 0, 0) paint(abc) repeat scroll 0% 0% / auto padding-box border-box"

返回的是集合

需要使用模糊匹配才行。

三、其他方法

核心思想类似:

document.head.setAttribute('style', 'filter: blur(5px)');
result = !!document.head.style.filter;

Chrome和IE下验证检测结果图:

Chrome下

IE浏览器下

总结一下

不考虑兼容性,对CSS的进行检测使用CSS.supports()方法,要检测IE浏览器使用赋值取值法。

欢迎补充其他方法。

(本篇完)

分享到:


发表评论(目前6 条评论)

  1. 渣渣giao说道:

    为啥不直接创建元素,然后赋值。
    var div = document.createElement(‘div’);
    div.style.display=”flex”;
    if(div.style.display !== ‘flex’){
    insertLink(‘/ie/css/ie9.css’);
    }

  2. albert说道:

    学习了

  3. QWER说道:

    大人,食大便了!

  4. 风缘说道:

    可以通过 document.getElementById(“content”).style[“xxx”] 方法检测该属性名是否被支持,这个目前兼容性好吗?

  5. __________________切说道:

    先赞再看