创建新MouseEvent的老式方式看起来如何?

时间:2017-03-22 07:46:38

标签: javascript javascript-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说鼠标左键已被“击落”。

1 个答案:

答案 0 :(得分: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);
};