zoukankan      html  css  js  c++  java
  • CSS 模块的侦测

    CSS 的规格发展太快,新的模块层出不穷。不同浏览器的不同版本,对 CSS 模块的支持情况都不一样。有时候,需要知道当前浏览器是否支持某个模块,这就叫做“CSS模块的侦测”。

    一个比较普遍适用的方法是,判断元素的style对象的某个属性值是否为字符串。

    typeof element.style.animationName === 'string';
    typeof element.style.transform === 'string';

    如果该 CSS 属性确实存在,会返回一个字符串。即使该属性实际上并未设置,也会返回一个空字符串。如果该属性不存在,则会返回undefined

    document.body.style['maxWidth'] // ""
    document.body.style['maximumWidth'] // undefined

    上面代码说明,这个浏览器支持max-width属性,但是不支持maximum-width属性。

    注意,不管 CSS 属性名的写法带不带连词线,style属性上都能反映出该属性是否存在。

    document.body.style['backgroundColor'] // ""
    document.body.style['background-color'] // ""

    另外,使用的时候,需要把不同浏览器的 CSS 前缀也考虑进去。

    var content = document.getElementById('content');
    typeof content.style['webkitAnimation'] === 'string'

    这种侦测方法可以写成一个函数。

    function isPropertySupported(property) {
      if (property in document.body.style) return true;
      var prefixes = ['Moz', 'Webkit', 'O', 'ms', 'Khtml'];
      var prefProperty = property.charAt(0).toUpperCase() + property.substr(1);
    
      for(var i = 0; i < prefixes.length; i++){
        if((prefixes[i] + prefProperty) in document.body.style) return true;
      }
    
      return false;
    }
    
    isPropertySupported('background-clip')
    // true
  • 相关阅读:
    January 25th, 2018 Week 04th Thursday
    January 24th, 2018 Week 04th Wednesday
    January 23rd, 2018 Week 04th Tuesday
    January 22nd, 2018 Week 04th Monday
    January 21st, 2018 Week 3rd Sunday
    January 20th, 2018 Week 3rd Saturday
    January 19th, 2018 Week 3rd Friday
    January 18th, 2018 Week 03rd Thursday
    January 17th, 2018 Week 03rd Wednesday
    January 16th, 2018 Week 03rd Tuesday
  • 原文地址:https://www.cnblogs.com/ziyoublog/p/9914966.html
Copyright © 2011-2022 走看看