MouseEvent 在 Internet Explorer 中不工作

MouseEvent not working in Internet Explorer

是我吗?是我的IE吗?或者为什么这段代码不能在 IE 11 上运行:

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) 上得到 "Object doesn't support this action"。我不得不想出一个解决方法,但我只是不明白为什么以前的代码不起作用(顺便说一下,以前的代码来自这里: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 event = new XXXXEvent(...) ),而不是依赖已弃用的方法。

您提供的 link 中的 MSDN 文档表明 DOM L4 事件构造函数模式的新语法:

Applies to Internet Explorer for Windows 10 Technical Preview and later.

这与您使用的 IE 版本不同。所以预计IE11不支持这个功能

有一个 polyfill 可以让它在 IE 中工作。

除了该代码中的 try catch 块需要如下所示:

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

我将此更正提交到他们的网站。

另一种选择是利用 MDN polyfills package

安装

npm i mdn-polyfills --save

用法

import 'mdn-polyfills/MouseEvent';

const link = document.createElement("a");
link.download = fileName;
link.href = url;
link.dispatchEvent(new MouseEvent("click", {bubbles: true, cancelable: true, view: window}));