在编写一些拖放代码时,我想取消鼠标向上处理程序中的单击事件。我认为防止默认应该能起到作用,但单击事件仍然被激发。
有没有办法做到这一点?
这不起作用:
<div id="test">test</div>
<script>
$("#test").mouseup (function (e) {
var a = 1;
e.preventDefault();
});
$("#test").click (function (e) {
var a = 2;
});
发布于 2012-01-19 22:18:07
我也有同样的问题,也没有找到解决方案。但我想出了一个似乎可行的方法。
由于onMouseUp处理程序似乎不能通过preventDefault或stopEvent或任何其他方式取消对链接的单击,因此我们需要使该链接取消自身。这可以通过编写onclick属性来完成,该属性在拖动开始时向a标记返回false,并在拖动结束时删除它。
由于onDragEnd或onMouseUp处理程序是在浏览器解释单击之前运行的,因此我们需要检查拖动的结束位置以及单击了哪个链接,等等。如果它在被拖动的链接之外结束(我们拖动了链接以便光标不再位于该链接上),我们将删除onDragEnd中的onclick处理程序;但如果它在光标位于被拖动的链接上的位置结束(将启动单击),我们将让onclick处理程序自行删除。够复杂的,对吧?
不是完整的代码,只是向你展示一下想法:
// event handler that runs when the drag is initiated
function onDragStart (args) {
// get the dragged element
// do some checking if it's a link etc
// store it in global var or smth
// write the onclick handler to link element
linkElement.writeAttribute('onclick', 'removeClickHandler(this); return false;');
}
// run from the onclick handler in the a-tag when the onMouseUp occurs on the link
function removeClickHandler (element) {
// remove click handler from self
element.writeAttribute('onclick', null);
}
// event handler that runs when the drag ends
function onDragEnds (args) {
// get the target element
// check that it's not the a-tag which we're dragging,
// since we want the onclick handler to take care of that case
if (targetElement !== linkElement) {
// remove the onclick handler
linkElement.writeAttribute('onclick', null);
}
}
我希望这能让你对如何实现这一目标有所了解。正如我所说的,这不是一个完整的解决方案,只是解释了概念。
发布于 2013-11-30 00:49:11
使用事件捕获阶段
在要取消单击事件的元素周围放置一个元素,并为其添加一个捕获事件处理程序。
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。
发布于 2014-06-18 05:36:18
有一个解决方案!
这种方法对我很有效(至少在chrome中是这样):
在mousedown
上,我向当前正在移动的元素添加一个类,而在mouseup
上,我删除了这个类。
该类所做的全部工作就是设置pointer-events:none
不知何故,这使它工作,点击事件不会被激发。
https://stackoverflow.com/questions/8643739
复制相似问题