JavaScript快速检测浏览器对CSS3特性的支持情况

  项目中使用动画效果在IE9下不支持,所以写了个判断浏览器是否支持动画的函数,进而扩展到下面判断浏览器支持任一特定CSS3属性的函数。

function supportAnimation(){
    var domPrefixes = 'webkit Moz o ms Khtml'.split(' '),
        len = domPrefixes.length,
        htmlStyle = document.documentElement.style;
    if(htmlStyle.animationName !== undefined) return true;
    for(var i = 0; i < len; i++){
        if(htmlStyle[domPrefixes[i] + "AnimationName"] !== undefined){
            return true;
        }
    }
    return false;
}

1、背景:

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

2、检测方法:

下面的方法可以使用脚本判断浏览器是否支持某一个CSS3属性:

/*
  判断浏览器是否支持某一个CSS3属性 
  @param {String} 属性名称 
  @return {Boolean} true/false 
*/
function supportCss3(style) { 
    var prefix = ['webkit', 'Moz', 'ms', 'o'], 
        i, 
        humpString = [], 
        htmlStyle = document.documentElement.style, 
        _toHumb = function (string) { 
                    return string.replace(/-(w)/g, function ($0, $1) { 
                        return $1.toUpperCase(); 
                    }); 
                }; 
    if(style in htmlStyle) return true;
    for (i in prefix){
        humpString.push(_toHumb(prefix[i] + '-' + style));
    }
    humpString.push(_toHumb(style)); 
    for (i in humpString) {
        if(humpString[i] in htmlStyle) return true;
    }
    return false; 
}

3、使用方法:

window.onload=function(){
    alert(supportCss3('animation-play-state'));
}

 4、原理:

(1)浏览器所支持的属性的数组列表:

(2)检查属性text是否包含在数组中,如果是,直接返回true。

(3)检查各种前缀,比如webkit加上text,即webkitTransition,如果包含在style中,返回true。

值得注意的是在CSS中属性名为:-webkit-transition,但是在DOM的style中 ,却是对应webkitTransition。

原文地址:https://www.cnblogs.com/goloving/p/7156173.html