2015-03-02 200 views
15

是我嗎?它是我的IE嗎?或者爲什麼這個代碼不工作的IE 11:MouseEvent不能在Internet Explorer中工作

var clicker = new MouseEvent("click", { 
    'bubbles': true, 
    'cancelable': true, 
    'view': window, 
    'detail': 0, 
    'screenX': 0, 
    'screenY': 0, 
    'clientX': 0, 
    'clientY': 0, 
    'ctrlKey': false, 
    'altKey': false, 
    'shiftKey': false, 
    'metaKey': false, 
    'button': 0, 
    'relatedTarget': null 
}); 

我收到「對象不支持此操作」上的控制檯(F12)。我不得不提出一個解決方法,但我只是不明白爲什麼以前的代碼不工作(順便說一句,前面的代碼來自這裏:https://msdn.microsoft.com/en-us/library/ie/dn905219(v=vs.85).aspx(創建和解僱合成事件)。 解決方法:

if (typeof MouseEvent !== 'function') { 
    (function(){ 
     var _MouseEvent = window.MouseEvent; 
     window.MouseEvent = function (type, dict){ 
      dict = dict | {}; 
      var event = document.createEvent('MouseEvents'); 
      event.initMouseEvent(
        type, 
        (typeof dict.bubbles == 'undefined') ? true : !!dict.bubbles, 
        (typeof dict.cancelable == 'undefined') ? false : !!dict.cancelable, 
        dict.view || window, 
        dict.detail | 0, 
        dict.screenX | 0, 
        dict.screenY | 0, 
        dict.clientX | 0, 
        dict.clientY | 0, 
        !!dict.ctrlKey, 
        !!dict.altKey, 
        !!dict.shiftKey, 
        !!dict.metaKey, 
        dict.button | 0, 
        dict.relatedTarget || null 
      ); 
      return event; 
     } 
    })(); 
} 

這筆交易,我想棄用的createEvent/initXXXXEvent儘可能遷移到新形式(VAR的事件=新XXXXEvent(...)),而不是依靠過時方法。

回答

10

MSDN文檔從您提供的鏈接指示DOM L4事件構造函數模式的新語法:

適用於Windows 10 Technical Preview的Internet Explorer和稍後的 。

這是與您使用的IE版本不同的版本。因此,預計IE11不支持此功能

+3

啊!我的大腦想要閱讀IE 10 ......與Windows 10的IE完全不同。感謝您指出這個問題。 – 2015-03-03 04:34:21

+7

這是一個解決方法:http://www.codeproject.com/Tips/893254/JavaScript-Triggering-Event-Manually-in-Internet-E – geraldo 2016-02-17 12:21:41

3

有一個polyfill使其在IE中工作。

除了在代碼try catch塊需要看起來像這樣:

try { 
    new CustomEvent('test'); 
    return false; // No need to polyfill 
} catch (e) { 
    // Need to polyfill - fall through 
} 

我提交了該糾正他們的網站。

相關問題