Javascript click and mousedown conflicting

蓝咒 提交于 2019-12-10 00:50:31

问题


I have a certain scenario where I'm using click to insert a div and then mousedown on that div for dragging it around. I have bound the click to the parent container, and the mousedown on the div itself. But when I mousedown on the div, it fires the click on the parent as well, hence inserting multiple divs instead of dragging the already added div!

Is there a way to solve this issue? I can't unbind click, since I need to add 2 divs using the click, and then bind mousedown on these.

Update: I'm using selector.on(event, handler) type of binding.


回答1:


Try this way. event.stopPropagation does not stop the click event from firing after mousedown. Mousedown and click events are not related to each other.

var mousedownFired = false;

$("#id").on('mousedown', function(event) {
    mousedownFired = true;
    //code
});

$("#id").on('click', function(event) {
    if (mousedownFired) {
        mousedownFired = false;
        return;
    }
    //code
});

Update:

Mouse events are triggered like this:

  1. mousedown

  2. click

  3. mouseup

If mousedown is triggered, the mousedownFired variable will be set to true. Then in the click event, it will return (i.e. not continue processing the click event), and the mousedownFired variable will be reset to false, so future click events will fire normally. Not going to consider two mousedown or two click events.




回答2:


What you likely want to do is attach the event handlers to the parent container rather than the individual child divs. By doing this, as new children are created, you don't need to add additional event handlers.

For example:

$("#parentDiv").on('click','.childDiv',function() {
    event.stopPropagation();
}).on('mousedown','.childDiv',function() {
    // your dragging code
});

When you provide a selector to the .on() function, the function passed is called for descendants that match that selector.




回答3:


You can use event.stopPropagation().

Example :

$("#button").mousedown(function(event){
event.stopPropagation();
// your code here
});

$("#button").click(function(event){
event.stopPropagation();
// your code here
});

Look at this page http://api.jquery.com/event.stopPropagation/




回答4:


            var timestamp = 0;
    jQuery('ul.mwDraggableSelect a',element).mousedown(function(event){
        timestamp = new Date().getTime();
    });

    jQuery('ul.mwDraggableSelect a',element).click(function(event){
        var interval = 400;//if a mousedown/mouseup is longer then interval, dont process click
        var timestamp2 = new Date().getTime();
        if((timestamp2 - timestamp)>interval){ return false; }

                    /* your code here */
            });


来源:https://stackoverflow.com/questions/14618478/javascript-click-and-mousedown-conflicting

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!