2016-09-01 75 views
0

我有這樣的javascript代碼:如何檢測document.addEventListener支持在JavaScript

initializeEventHandlers: function() { 
     if (typeof document.implementation != "undefined" && 
     document.implementation.hasFeature("HTML", "1.0") && 
     document.implementation.hasFeature("Events", "2.0") && 
     document.implementation.hasFeature("CSS", "2.0")) { 
     document.addEventListener("mouseup", this._mouseUpHandler.bindAsEventListener(this), false); 
     document.addEventListener("mousemove", this._mouseMoveHandler.bindAsEventListener(this), false); 
     } 
     else { 
     document.attachEvent("onmouseup", this._mouseUpHandler.bindAsEventListener(this)); 
     document.attachEvent("onmousemove", this._mouseMoveHandler.bindAsEventListener(this)); 
     } 
    } 

,在大多數瀏覽器上運行,但是當我使用IE11失敗。我知道這是因爲IE11移除了對attachEvent的支持,並且IE11落入了else條件。我也看到hasFeature已被棄用,所以我不知道如何最好地檢測addEventListner支持。

+0

什麼是您必須支持的最古老的瀏覽器? –

+0

注意:document.implementation.hasFeature已棄用,並且在很多情況下始終返回true:p –

回答

1

以下代碼適用於IE11和Firefox,但是它適用於其他/舊版瀏覽器嗎?

initializeEventHandlers: function() { 
     if (document.addEventListener) { 
     document.addEventListener("mouseup", this._mouseUpHandler.bindAsEventListener(this), false); 
     document.addEventListener("mousemove", this._mouseMoveHandler.bindAsEventListener(this), false); 
     } 
     else if (document.attachEvent) { 
     document.attachEvent("onmouseup", this._mouseUpHandler.bindAsEventListener(this)); 
     document.attachEvent("onmousemove", this._mouseMoveHandler.bindAsEventListener(this)); 
     } 
    } 
+0

https://gist.github.com/eirikbacker/2864711/946225eb3822c203e8d6218095d888aac5e1748e https://github.com/termi/ES5-DOM- SHIM/ – Tschallacka

+0

這是檢查這種情況的典型方法(注意,首先檢查addEventListener是否符合標準,然後是舊IE特定情況)。它應該基本上在所有的瀏覽器上運行,除了二十年前的瀏覽器。 –