【问题标题】:Check if the browser supports document.querySelectorAll in JavaScript检查浏览器是否支持 JavaScript 中的 document.querySelectorAll
【发布时间】:2014-04-12 18:28:32
【问题描述】:

虽然现在大多数现代浏览器都支持document.querySelectorAll(),但您可能会在使用旧版本的 Internet Explorer 时遇到问题。检查浏览器是否支持某个功能的明显方法是:

if(document.querySelectorAll){
    //some random code
}

但据我了解,某些浏览器(例如 IE8)不支持某些属性,例如“body *”。有没有更好的方法来检查document.querySelectorAll('body *') 是否真的有效?

【问题讨论】:

  • IE8 只支持 CSS2 选择器,但 body * 不是 CSS2 选择器吗?
  • 正是我遇到的问题。我正在寻找一种方法来测试它。
  • body * 在 IE8 中做了什么?
  • 我想你不明白,body * 不能在 IE8 中工作,对我来说它看起来像一个 CSS2 选择器,应该可以工作吗?
  • 控制台说什么?

标签: javascript internet-explorer dom cross-browser document


【解决方案1】:

使用 typeof 进行检查:

 if(typeof(document.querySelectorAll) != 'undefined'){
      //some random code
 }

【讨论】:

    【解决方案2】:

    document.querySelectorAll 将抛出任何不受支持的选择器,因此您可以简单地使用 try-catch 块。

    【讨论】:

      【解决方案3】:

      检查浏览器是否支持,不用try-catch:

      function QuerySelectors() {
        return (document['querySelector']&&document['querySelectorAll'])!=null;
      }
      

      function QuerySelectors(){
        return typeof(document['querySelector'])=='function'&&typeof(document['querySelectorAll'])=='function';
      }
      

      阅读更多 > Reference

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-03-11
        • 2020-01-04
        • 2018-06-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-07-06
        相关资源
        最近更新 更多