【问题标题】:How to detect if browser support specified css pseudo-class?如何检测浏览器是否支持指定的css伪类?
【发布时间】:2012-01-21 20:21:42
【问题描述】:

通过 JavaScript 检测浏览器中任何 css 伪类的支持是什么概念?确切地说,我想检查用户的浏览器是否支持 :checked 伪类,因为我已经制作了一些带有复选框的 CSS 弹出窗口,并且需要为旧浏览器做回退。

回答:我发现在 Modernizr "Additional Tests" 中测试 css 选择器的 method 已经实现。

【问题讨论】:

  • Modernizr 检测到很多类似的东西。
  • 我知道 Modernizr,但它没有对 css3 伪类支持的测试,只有 ::before 等伪元素。

标签: javascript css detection pseudo-class browser-feature-detection


【解决方案1】:

stylesheet.insertRule(rule, index) 方法会在规则无效时抛出错误。所以我们可以使用它。

var support_pseudo = function (){
    var ss = document.styleSheets[0];
    if(!ss){
        var el = document.createElement('style');
        document.head.appendChild(el);
        ss = document.styleSheets[0];
        document.head.removeChild(el);
    }
    return function (pseudo_class){
        try{
            if(!(/^:/).test(pseudo_class)){
                pseudo_class = ':'+pseudo_class;
            }
            ss.insertRule('html'+pseudo_class+'{}',0);
            ss.deleteRule(0);
            return true;
        }catch(e){
            return false;
        }
    };
}();


//test
support_pseudo(':hover'); //true
support_pseudo(':before'); //true
support_pseudo(':hello'); //false
support_pseudo(':world'); //false

【讨论】:

    【解决方案2】:

    对于仍在寻找此问题的快速解决方案的任何人,我根据此线程中的其他一些答案拼凑了一些东西。我的目标是让它简洁。

    function supportsSelector (selector) {
      const style = document.createElement('style')
      document.head.appendChild(style)
      try {
        style.sheet.insertRule(selector + '{}', 0)
      } catch (e) {
        return false
      } finally {
        document.head.removeChild(style)
      }
      return true
    }
    
    supportsSelector(':hover') // true
    supportsSelector(':fake') // false
    

    【讨论】:

      【解决方案3】:

      您可以简单地检查是否应用了您的带有伪类的样式。

      类似这样的:http://jsfiddle.net/qPmT2/1/

      【讨论】:

      • 发现已经实现了 method 在 Modernizr "Additional Tests" 中测试 css 选择器。哦,天哪,为什么它不在核心中?
      • 可行的解决方案,但有点丑
      【解决方案4】:

      如果您可以使用 Javascript,则可以跳过检测并直接使用 shim:Selectivizr

      【讨论】:

      • 最好不要使用Selectivizr,因为在渲染页面之前解析CSS会导致性能下降。
      猜你喜欢
      • 1970-01-01
      • 2013-06-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-11
      • 2014-10-05
      • 2011-12-12
      相关资源
      最近更新 更多