1

Js判读浏览器是否支持 CSS 属性

 1 month ago
source link: https://www.fly63.com/article/detial/12671
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

更新日期: 2024-03-01阅读: 407标签: 属性分享

扫一扫分享

css3的出现让浏览器的表现更加的丰富多彩,表现冲击最大的就是动画了,在日常书写动画的时候,很有必要去事先判断浏览器是否支持,尤其是在写CSS3动画库的时候。比如transition的animation-play-state,就只有部分浏览器支持。

浏览器是否支持某一个CSS3属性可以通过编写JavaScript代码来判断。以下是一个示例函数,用于检测浏览器是否支持特定的CSS3属性:

function supportCss(style) {
let prefix = ['webkit', 'Moz', 'ms', 'o']
let hump = []
let htmlStyle = document.documentElement.style
let toHumb = function(string) {
return string.replace(/-(\w)/g, ($0, $1)=>{
return $1.toUpperCase()
})
}
for (let i in prefix)
hump.push(toHumb(prefix[i] + '-' + style))
hump.push(toHumb(style))
for (let i in hump)
if (hump[i] in htmlStyle) return true
return false
}

使用此函数时,只需将要检测的CSS3属性作为参数传递给函数即可,例如:

supportCss('animation-play-state') //true

此函数会遍历各种浏览器前缀(如-webkit-、-moz-等)和无前缀的属性名,检查它们是否存在于document.documentElement.style对象中。如果存在,则说明浏览器支持该CSS3属性,函数返回true;否则,返回false。

请注意,这种方法并不是完全可靠的,因为有些浏览器可能支持某个CSS3属性但无法正确识别其名称。此外,随着浏览器更新和CSS标准的演进,某些属性可能会被弃用或更改。因此,在使用此函数时,建议结合其他方法(如查阅浏览器文档或使用在线工具)来验证结果。

链接: https://www.fly63.com/article/detial/12671


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK