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); } })();