检测浏览器是否支持某个css属性
以浏览器是否支持translate3d 为例说明,当然现代浏览器已经支持该属性。如果浏览器实现了带有前缀的某个属性,比如说支持-webkit-transform
,但是不支持直接写transform
,可以通过检测浏览器engine,给属性加上特殊的前缀
let docStyle = document.documentElement.style
let translate3d = false
let engine
if (window.opera && Object.prototype.toString.call(opera) === '[object Opera]') {
engine = 'presto'
} else if ('MozAppearance' in docStyle) {
engine = 'gecko'
} else if ('WebkitAppearance' in docStyle) {
engine = 'webkit'
} else if (typeof navigator.cpuClass === 'string') {
engine = 'trident'
}
let cssPrefix = {trident: '-ms-', gecko: '-moz-', webkit: '-webkit-', presto: '-o-'}[engine]
let vendorPrefix = {trident: 'ms', gecko: 'Moz', webkit: 'Webkit', presto: 'O'}[engine]
let helperElem = document.createElement('div')
let perspectiveProperty = vendorPrefix + 'Perspective'
let transformProperty = vendorPrefix + 'Transform'
let transformStyleName = cssPrefix + 'transform'
let transitionProperty = vendorPrefix + 'Transition'
let transitionStyleName = cssPrefix + 'transition'
let transitionEndProperty = vendorPrefix.toLowerCase() + 'TransitionEnd'
// 可能带prefix前缀也可能不带
if (helperElem.style[perspectiveProperty] !== undefined) {
translate3d = true
}
胖胖熊笔记,笔记已迁移