我读到了这个: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
说鼠标左键已被“击落”。
答案 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);
};