我需要在元素上发生mousedown
事件后捕获鼠标事件。
在MDN setCapture上,我看不到有关未实现setCapture()
的任何提及
在Chrome中,但是尝试运行提供的the example会生成Uncaugt TypeError
,因为e.target.setCapture
本质上是Chrome中的undefined
。
function init() {
var btn = document.getElementById("myButton");
btn.addEventListener("mousedown", mouseDown, false);
btn.addEventListener("mouseup", mouseUp, false);
}
function mouseDown(e) {
e.target.setCapture();
e.target.addEventListener("mousemove", mouseMoved, false);
}
function mouseUp(e) {
e.target.removeEventListener("mousemove", mouseMoved, false);
}
function mouseMoved(e) {
var output = document.getElementById("output");
output.innerHTML = "Position: " + e.clientX + ", " + e.clientY;
}
Chrome中的等效API是什么?
最佳答案
我终于想出了一个完整的ES2015解决方案(解释为on my blog),该解决方案可以捕获
鼠标事件并有效禁用寄生悬停和指针光标
按下鼠标按钮时更改。
从附加到captureMouseEvents(e)
事件的事件处理程序中调用mousedown
:
const EventListenerMode = {capture: true};
function preventGlobalMouseEvents () {
document.body.style['pointer-events'] = 'none';
}
function restoreGlobalMouseEvents () {
document.body.style['pointer-events'] = 'auto';
}
function mousemoveListener (e) {
e.stopPropagation ();
// do whatever is needed while the user is moving the cursor around
}
function mouseupListener (e) {
restoreGlobalMouseEvents ();
document.removeEventListener ('mouseup', mouseupListener, EventListenerMode);
document.removeEventListener ('mousemove', mousemoveListener, EventListenerMode);
e.stopPropagation ();
}
function captureMouseEvents (e) {
preventGlobalMouseEvents ();
document.addEventListener ('mouseup', mouseupListener, EventListenerMode);
document.addEventListener ('mousemove', mousemoveListener, EventListenerMode);
e.preventDefault ();
e.stopPropagation ();
}
请注意,
pointer-events: none
样式可防止任何组件接收鼠标事件。
关于javascript - 在Chrome中替换element.setCapture?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37810642/