2015-03-02 202 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 
} 

我提交了该纠正他们的网站。

相关问题