javascript - 创建新 MouseEvent 的老式方法是什么样子的?

标签 javascript dom-events

我读到了这个:https://developer.mozilla.org/en-US/docs/Web/API/Document/createEvent在旧版本中,他们在呈现旧方式时省略了一些细节。

我有特定的代码:

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

在某些环境下无法正确执行。因此我用老式的方式写了一个版本:

HTMLElement.prototype.mouseDownLeftButton = function () {
    var event = document.createEvent("MouseEvent");
    event.initEvent("mousedown", true, false);
    event.setAttribute("which", 1);//how to do it correctly?
    event.setAttribute("view", window);//how to do it correctly?
    this.dispatchEvent(event);
};

但不幸的是我得到:

TypeError: event.setAttribute is not a function

问题:如何正确设置 which1viewwindow > 以旧时尚?为了澄清 which: 1 表示鼠标左键已被“按下”。

最佳答案

您需要使用event.currentTarget.setAttribute并仅使用event.which属性,它将检测

1 - Left
2 - Middle
3 - Right

JS

HTMLElement.prototype.mouseDownLeftButton = function () {
    var event = document.createEvent("MouseEvent");
    event.initEvent("mousedown", true, false);
    event.setAttribute("which", event.which);//how to do it correctly?
    event.setAttribute("view", window);//how to do it correctly?
    this.dispatchEvent(event);
};

关于javascript - 创建新 MouseEvent 的老式方法是什么样子的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42945571/

相关文章:

javascript - 如何将数据从 javascript 导入到 mongoDB 数据库中?

javascript - 仅在媒体大小超过 980px 时将 Wordpress Logo 移动到内联主导航中心(无序列表)

javascript - Vanilla Js : Start a while loop in one event, 用第二个事件打破它? ('mouseover'开始, 'mouseout'设置循环条件为假)

javascript - IE8 中的 JSON 语法错误?

javascript - Opencart - jQuery 购物车总更新 - 修改输出

javascript - Jquery 对选择器的响应差异 $ ('#tag_field_2' ) 和 $ ('input[style]' )[0]

javascript - 与引导 slider 交互后启用按钮

javascript - 循环中的 addEventHandler() 有意外结果

javascript - JavaScript 中不允许使用的方法

javascript - 如何获取 onclick 函数在 JavaScript 中被调用的位置