簡體   English   中英

JavaScript - 測試瀏覽器是否支持 getAttributeNode、setAttributeNode 和 createAttribute

[英]JavaScript - Test if getAttributeNode, setAttributeNode and createAttribute are supported by browser

如何檢查瀏覽器是否支持 getAttributeNode、setAttributeNode 和 createAttribute 函數?

我需要通過 JavaScript 檢測 IE6 和 IE5.5 之間的限制,而無需 Navigator User Agent(使用 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
        }

您可以使用in運算符來檢查對象是否具有某些屬性:

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

myElement應該是對某個元素的引用,例如document.documentElement

正確的方法是檢查Element.prototypeDocument.prototype ,但舊的 IE 不會公開它們。 因此,您應該在某些情況下進行檢查,並假設它也適用於其他情況。

注意上面的代碼只測試屬性的存在。 如果你想更安全,你也可以使用typeof來檢查它們是否是函數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM