我读到了这个: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
问题:如何正确设置 which
为 1
和 view
为 window
> 以旧时尚?为了澄清 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/