简体   繁体   English

如何检测浏览器是否支持指定的css伪类?

[英]How to detect if browser support specified css pseudo-class?

What's concept of detecting support of any css pseudo-class in browser through JavaScript?通过 JavaScript 检测浏览器中任何 css 伪类的支持是什么概念? Exactly, I want to check if user's browser supports :checked pseudo-class or not, because I've made some CSS-popups with checkboxes and needs to do fallbacks for old browsers.确切地说,我想检查用户的浏览器是否支持:checked伪类,因为我制作了一些带有复选框的 CSS 弹出窗口,并且需要为旧浏览器做回退。

ANSWER: I'm found already implemented method of testing css selectors in a Modernizr "Additional Tests" .回答:我发现已经在 Modernizr “附加测试”中实现了测试 css 选择器的方法

stylesheet.insertRule(rule, index) method will throw error if the rule is invalid.如果规则无效,stylesheet.insertRule(rule, index)方法将抛出错误。 so we can use it.所以我们可以使用它。

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

You can simply check if your style with pseudo-class was applied.您可以简单地检查是否应用了伪类的样式。

Something like this: http://jsfiddle.net/qPmT2/1/像这样的东西: http : //jsfiddle.net/qPmT2/1/

For anyone still looking for a quick solution to this problem, I cribbed together something based on a few of the other answers in this thread.对于仍在寻找此问题的快速解决方案的任何人,我根据此线程中的其他一些答案将一些内容汇总在一起。 My goal was to make it succinct.我的目标是让它简洁。

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM