js判断浏览器是否支持css3属性

作者:结一 日期:2013-12-10 点击:52

var cssSupports = (function() {
        var div = document.createElement('div'),
                vendors = 'Khtml O Moz Webkit'.split(' '),
                len = vendors.length;
        return function(prop) {
                if ( prop in div.style ) return true;
                if ('-ms-' + prop in div.style) return true;
                
                prop = prop.replace(/^[a-z]/, function(val) {
                        return val.toUpperCase();
                });

                while(len--) {
                        if ( vendors[len] + prop in div.style ) {
                        return true;
                }
        }
                return false;
        };
})();

下面简单说下两个实例:

border-radius

判断浏览器是否支持border-radius,支持则给html添加class为border-radius,否则添加class为no-border-radius

if(cssSupports('borderRadius')){
        document.documentElement.className += ' border-radius';
}else{
        document.documentElement.className += ' no-border-radius';
}

flex

因为这个flex是出现在display的值上面的,而我们上面的方法其实只适用于属性,所以直接是不行的,我们可以通过曲线的方法来判断,和 flex相关的还有很多其他的属性如order,align-content,align-item,align-slef等,我们就用最简单的 order来曲线判断是否支持flex吧。(注意因为flex除了标准版本外,还有其他两个版本,这里只挑标准的属性判断,如果你对flex的版本比较迷 糊,可以查阅终极Flexbox属性查询列表

if(cssSupports('order')){
        document.documentElement.className += ' flex';
}else{
        document.documentElement.className += ' no-flex';
}

如果你对上面那段js有点不明白,你可以在控制台运行这段代码,就会看到所有style的属性

(function(){
        var oDiv = document.createElement('div');

        for(var prop in oDiv.style){
                console.log(prop);
        }
})();