问题描述
编写一些拖放代码,我想取消我的mouseup处理程序中的点击事件。
Writing some drag&drop code, I'd like to cancel the click events in my mouseup handler. I figured preventing default should do the trick, but the click event is still fired.
有没有办法做到这一点?
Is there a way to do this?
这不起作用:
<div id="test">test</div>
<script>
$("#test").mouseup (function (e) {
var a = 1;
e.preventDefault();
});
$("#test").click (function (e) {
var a = 2;
});
推荐答案
我有同样的问题,解决方案。但我想出了一个似乎工作的黑客。
I had the same problem and didn't found a solution either. But I came up with a hack that seems to work.
由于onMouseUp处理程序似乎无法取消对具有preventDefault或stopEvent或任何东西的链接的点击,因此我们需要使链接取消本身。这可以通过编写一个onclick属性来完成,当拖动开始时,返回false到a-tag,当拖动结束时将其删除。
Since the onMouseUp handler doesn't seem to be able to cancel the click on a link with preventDefault or stopEvent or anything, we need to make the link cancel itself. This can be done by writing an onclick attribute which returns false to the a-tag when the drag begins, and removing it when the drag ends.
由于onDragEnd或onMouseUp处理程序在浏览器解释点击之前运行,因此我们需要在拖动结束和点击链接时进行一些检查上。如果它结束在拖动的链接之外(我们拖动链接,以使光标不在链接上),我们删除onDragEnd中的onclick处理程序;但如果它结束光标在拖动的链接(点击将启动),我们让onclick处理程序删除自己。非常复杂,对吗?
And since the onDragEnd or onMouseUp handlers are run before the click is interpreted by the browser, we need to do some checking where the drag ends and which link is clicked and so on. If it ends outside the dragged link (we dragged the link so that the cursor isn't on the link anymore), we remove the onclick handler in the onDragEnd; but if it ends where the cursor is on the dragged link (a click would be initiated), we let the onclick-handler remove itself. Complicated enough, right?
不完全的代码,只是为了向您展示这个想法:
NOT COMPLETE CODE, but just to show you the idea:
// 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);
}
}
我希望这可以让您了解如何完成。正如我所说,这不是一个完整的解决方案,只是解释的概念。
I hope this gives you an idea of how this can be accomplished. As I said, this is not a complete solution, just explaining the concept.
这篇关于在mouseup事件处理程序中取消单击事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!