Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/vb.net/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何检测浏览器是否支持指定的css伪类?_Javascript_Css_Detection_Pseudo Class_Browser Feature Detection - Fatal编程技术网

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

Javascript 如何检测浏览器是否支持指定的css伪类?,javascript,css,detection,pseudo-class,browser-feature-detection,Javascript,Css,Detection,Pseudo Class,Browser Feature Detection,通过JavaScript检测浏览器中任何css伪类的支持的概念是什么?确切地说,我想检查用户的浏览器是否支持:是否选中了伪类,因为我已经制作了一些带有复选框的CSS弹出窗口,并且需要为旧浏览器进行回退 回答:我发现我已经在Modernizer中实现了测试css选择器的功能。如果你对使用Javascript没问题,你可以跳过检测,直接使用垫片:你可以简单地检查你的伪类样式是否被应用 类似这样的内容:如果规则无效,方法将抛出错误。所以我们可以使用它 var support_pseudo = func

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


回答:我发现我已经在Modernizer中实现了测试css选择器的功能。

如果你对使用Javascript没问题,你可以跳过检测,直接使用垫片:

你可以简单地检查你的伪类样式是否被应用

类似这样的内容:

如果规则无效,方法将抛出错误。所以我们可以使用它

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

对于仍然在寻找这个问题的快速解决方案的人,我根据这篇文章中的一些其他答案,抄袭了一些东西。我的目标是使它简洁明了

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

检测很多类似的东西。我知道Modernizr,但它没有css3伪类的测试支持,只有伪元素,如
::before
,等等。最好不要使用Selectivizr,因为在呈现页面之前解析CSS会降低性能。在Modernizr中已经实现了测试CSS选择器的功能。哦,天哪,为什么它不在核心?可行的解决方案,但有点难看