【问题标题】:JavaScript - Test if getAttributeNode, setAttributeNode and createAttribute are supported by browserJavaScript - 测试浏览器是否支持 getAttributeNode、setAttributeNode 和 createAttribute
【发布时间】:2015-11-24 05:06:48
【问题描述】:

如何查看浏览器是否支持getAttributeNode、setAttributeNode和createAttribute函数?

我需要通过 JavaScript 检测没有导航器用户代理的 IE6 和 IE5.5 之间的限制(使用 IEtester 或 IE 控制台模拟器)。

为什么?检查 Modernizr 浏览器支持

谢谢!


感谢奥里奥尔!但更具体地说,我需要这样的东西:

var support = true;
if(typeof(document.getElementsByClassName) === 'undefined'){
    support = false;
    }

if(support){
    // IE > 8
    }else{
    // IE <= 8  
        }

但不是 IE 8,而是 IE 5.5。 使用 getAttributeNode、setAttributeNode 和 createAttribute 代替 document.getElementsByClassName


找到了!!!使用来自http://diveintohtml5.info/detect.html的Oriol答案和视频检测方法

function supports() {
    var Element = document.createElement('div'),
    Q1 = !!Element.getAttributeNode,
    Q2 = !!Element.setAttributeNode,
    Q3 = !!document.createAttribute;
    return Q1 && Q2 && Q3;
}

if(supports()){
    // IE > 5.5
    }else{
    // IE <= 5.5
        }

【问题讨论】:

  • 你可以使用if(myElement.getAttributeNode &amp;&amp; myElement.setAttributeNode &amp;&amp; myElement.createAttribute){do something}

标签: javascript internet-explorer-6 modernizr jscript


【解决方案1】:

您可以使用in 运算符来检查对象是否具有某些属性:

'getAttributeNode' in myElement
&& 'setAttributeNode' in myElement
&& 'createAttribute' in document

myElement 应该是对某个元素的引用,例如document.documentElement.

正确的方法是签入Element.prototypeDocument.prototype,但旧的IE 不会暴露它们。因此,您应该检查某些情况,并假设它也适用于其他情况。

注意上面的代码只测试属性的存在。如果你想更安全你也可以使用typeof来检查它们是否是函数。

【讨论】:

  • 没有 DOM 元素?喜欢 document.getElementsByClassName?
  • @lucasgabmoreno getAttributeNodesetAttributeNode 仅在 Element 实例中可用,在 Document 实例中不可用。
  • 函数支持() { var Element = document.createElement('div'), Q1 = !!Element.getAttributeNode, Q2 = !!Element.setAttributeNode, Q3 = !!document.createAttribute;返回 Q1 && Q2 && Q3; } if(supports()){ // IE > 5.5 }else{ // IE
猜你喜欢
  • 1970-01-01
  • 2011-11-26
  • 2012-04-05
  • 2014-02-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-05
  • 2011-12-12
  • 2011-09-07
相关资源
最近更新 更多