编写一些拖放代码,我想取消 mouseup 处理程序中的单击事件。我认为防止默认应该可以解决问题,但点击事件仍然被触发。
有办法做到这一点吗?
<小时/>这不起作用:
<div id="test">test</div>
<script>
$("#test").mouseup (function (e) {
var a = 1;
e.preventDefault();
});
$("#test").click (function (e) {
var a = 2;
});
最佳答案
使用事件捕获阶段
在要取消其单击事件的元素周围放置一个元素,并向其添加捕获事件处理程序。
var btnElm = document.querySelector('button');
btnElm.addEventListener('mouseup', function(e){
console.log('mouseup');
window.addEventListener(
'click',
captureClick,
true // <-- This registeres this listener for the capture
// phase instead of the bubbling phase!
);
});
btnElm.addEventListener('click', function(e){
console.log('click');
});
function captureClick(e) {
e.stopPropagation(); // Stop the click from being propagated.
console.log('click captured');
window.removeEventListener('click', captureClick, true); // cleanup
}
<button>Test capture click event</button>
会发生什么:
在触发 button
上的单击事件之前,周围 div
上的单击事件会被触发,因为它在捕获阶段而不是冒泡阶段注册了自己。
然后,captureClick
处理程序会停止其 click
事件的传播,并阻止调用按钮上的 click
处理程序。正是您想要的。然后它会自行删除以进行清理。
捕获与冒泡:
捕获阶段从 DOM 根到叶子调用,而冒泡阶段从叶子到根调用(参见: wonderful explanation of event order )。
jQuery 总是将事件添加到冒泡阶段,这就是为什么我们需要在这里使用纯 JS 将捕获事件专门添加到捕获阶段。
请记住,IE 在 IE9 中引入了 W3C 的事件捕获模型,因此这不适用于 IE < 9。
<小时/>使用当前的事件 API,您无法在已添加的另一个事件处理程序之前向 DOM 元素添加新的事件处理程序。没有优先级参数和 there's no safe cross-browser solution to modify the list of event listeners .
关于javascript - 在 mouseup 事件处理程序中取消单击事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8643739/