例如,如果您有以下代码,当 mousedown
未发生时,mousemove
和 mouseup
事件是否会被销毁?
var el = document.getElementById('mydiv');
el.addEvenListener('mousedown', function(event){
initializeStuff();
document.onmousemove = function(event) {
event = event || window.event;
showDragAnimation();
};
doucment.onmouseup = function() {
showFinalPosition();
};
}, false);
最佳答案
不,它们不会被破坏 - mousedown
并不知道“没有发生”。由于 JS 不会并发运行,因此无论如何这都没有意义。
如果您的代码确实使用了 addEventListener
,它将严重泄漏事件处理程序并且您的应用程序会变得非常迟钝(每次点击都会变得更迟钝)。只有当您使用旧的 on...
属性覆盖以前的监听器时,您才能避免这种命运。
你会想要使用
function onmousedown(event) {
this.addEventListener("mousemove", onmousemove, false);
this.addEventListener("mouseup", onmouseup, false);
initializeStuff();
}
function onmousemove(event) {
showDragAnimation();
}
function onmouseup(event) {
this.removeEventListener("mousemove", onmousemove);
this.removeEventListener("mouseup", onmouseup);
showFinalPosition();
}
document.getElementById('mydiv').addEvenListener('mousedown', onmousedown, false);
关于javascript - 父事件结束时子听众是否被销毁?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28681601/