JS检测CSS属性浏览器是否支持的多种方法使用教程
一、原生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变量语法:
result = CSS.supports('--username: zhangxinxu');
result = CSS.supports('(--username: zhangxinxu)');
结果如下图所示:
可以看到有没有括号都支持。
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)');
可见,此时括号是必须的:
兼容性
和CSS @supports 规则兼容性一样,Edge12+支持。
尴尬的现状
实际开发的时候,需要使用到对CSS检测场景,往往都是针对低版本的IE浏览器,例如IE9-IE11。
于是尴尬的事情出现了,低版本的IE浏览器并不支持浏览器原生支持的 CSS.supports() 方法,于是,我们的实际需求并没有因为这个新的API而得到解决,不得不求助于其他方法。
二、JS赋值再取值的检测方法
这是我 张鑫旭 https://www.zhangxinxu.com 在实际项目中经常使用的一种方法,原理很简单,当浏览器不支持某个CSS属性的时候,就算你强制设置,获取的计算值也不会是你设置的属性值,还是检测浏览器是否支持CSS filter滤镜的例子。
我会这么处理:
document.head.style.filter = 'blur(5px)';
result = window.getComputedStyle(document.head).filter == 'blur(5px)';
我们看下上面代码在实际浏览器中的表现,首先是支持的Chrome浏览器, result 的值是 true :
然后是不支持的IE11浏览器, result 的值是 false :
此方法原理很简单,兼容性也非常好,实现的关键点就是使用 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浏览器下的结果:
兼容性
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下验证检测结果图:
总结一下
不考虑兼容性,对CSS的进行检测使用 CSS.supports() 方法,要检测IE浏览器使用赋值取值法。
本文地址: https://www.zhangxinxu.com/wordpress/?p=9051