javascript - MouseEventConstructor 不是构造函数

标签 javascript constructor mouseevent qunit

当我在本地执行测试时,它们毫无问题地通过了,但是当测试在服务器上进行时,我得到:

TypeError: MouseEventConstructor is not a constructor (evaluating 'new MouseEvent('mousedown',
EXEC : error : TypeError: MouseEventConstructor is not a constructor (evaluating 'new MouseEvent('mousedown', 
        {
            'which': 1,
            'view': window,
            'bubbles': true,
            'cancelable': true
        })')

代码:

HTMLElement.prototype.mouseDownLeftButton = function () {
        var event = new MouseEvent('mousedown',
        {
            'which': 1,
            'view': window,
            'bubbles': true,
            'cancelable': true
        });
        this.dispatchEvent(event);
    };

这完全没问题。还有其他方法可以创建 new MouseEvent 吗?

最佳答案

MDN 中有一个 polyfill 可以解决这个问题:

https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/MouseEvent#Polyfill

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

    // Polyfills DOM4 MouseEvent

    var MouseEvent = function (eventType, params) {
        params = params || { bubbles: false, cancelable: false };
        var mouseEvent = document.createEvent('MouseEvent');
        mouseEvent.initMouseEvent(eventType, params.bubbles, params.cancelable, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);

        return mouseEvent;
    };

    MouseEvent.prototype = Event.prototype;

    window.MouseEvent = MouseEvent;
})(window);

关于javascript - MouseEventConstructor 不是构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42929639/

相关文章:

javascript - 每次单击按钮时重置 setTimeout?

Javascript、数据表、jmhighlight 和多重搜索

javascript - jQuery 中使用函数处理程序 + 参数调用事件

c++ - 复制构造函数语法并显示构造函数的值

java - 用 Java 为简单的棋盘游戏创建图形

java - 如何使用鼠标拖动事件在java applet上绘制一个矩形并使其停留

javascript - 在安卓手机上,当访问市场 ://download url , 得到 "Unable to load the webpage"

c++ - 使用 enable_if 选择类构造函数

java - 属性初始化Java

javascript - 尝试获取鼠标单击 x 和 y pos 的准确值 - 得到 NaN