Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
298 views
in Technique[技术] by (71.8m points)

javascript - mouseUp event on drag

I have a link which has mousedown and mouseup handlers to animate some objects on page. When dragged (drag and drop) link fires mousedown event but it doesn't fire mouseup when released. is there a workaround for this problem?

Here is a example, if you click link normally it works but when you drag the link mouse up doesn't happen:

http://jsfiddle.net/hL3mg/1/

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Handling drags

Something crucial nobody mentions here is that there actually is an event to register the end of a drag, which as explained by the other answers is what's happening here. The event is called dragend, so you can simply do

$("a").on("dragend",function(){
    console.log("Drag End");
});

To register the end of the drag. The disadvantage of this is that you will still see a drag interface (in other words: the browser will show some UI to notify the user he's draggin).

Registering mouse up's

Note from 2020: This isn't a good answer, but I am not familiar anymore with jQuery, so can't update it well. I would guess that event.preventDefault() on the dragstart might or might not be relevant.

There is however also a way to register the sought after mouse ups, simply cancel the drag behaviour by returning false in the click event listener, and then register the mouseup on the document.

$("a").mousedown(function(){
    console.log("Mouse Down");
    return false;
});

$(document).mouseup(function(){
    console.log("Mouse Up");
});

The only remark that I do feel like I have to make is that in a stand alone jsfiddle this worked perfectly, in my own code it did not, so I am listening for both the mouseup and the dragend just to be sure.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...