Disable mousemove on click

本秂侑毒 提交于 2019-12-12 11:47:11

问题


I'm experimenting on a drag 'n' drop, this is my code here:

$('.box-title').live('mousedown click', function(e)
{
    var self = $(this);
    var Box = self.parent('#box');

    if(e.type == 'mousedown')
    {
        $(window).mousemove(function(e)
        {
            Box.css({ cursor: 'move', top: e.pageY - 15, left: e.pageX - 125 });
        });
    }
    else if(e.type == 'click')
    {
        Box.css({ cursor: 'default', top: e.pageY - 15, left: e.pageX - 125 });
    }
});

On mousedown, it should initiate the dragging effect by moving the mouse, after that if I want to dock/drop the box where I want it to me, I click on it it should disable the moving but if I click on it, it doesn't stop moving - just keeps following my mouse. How can you stop the dragging?


回答1:


You need to unbind the mousemove handler which is still attached currently, for example:

function setPos(e) {
  //can be $('#box') in this case...
  $(this).parent('#box').css({ cursor: 'move', top: e.pageY - 15, left: e.pageX - 125 });
}    
$('.box-title').live('mousedown click', function(e) {
    if(e.type == 'mousedown') {
        $(window).mousemove(setPos);
    }
    else if(e.type == 'click') {
        $(window).unbind('mousemove', setPos);
    }
});

Or, in jQuery 1.4.3+ that .live() handler can be a bit cleaner:

$('.box-title').live({
  mousedown: function() {
    $(window).mousemove(setPos);
  },
  click: function() {
    $(window).unbind('mousemove', setPos);
  }
});

As an aside, it appears you have multiple id="box" elements in the page...make sure to use classes in those cases, in this code $(this).parent('#box') would be $(this).closest('.box') instead.




回答2:


Try adding

$(window).unbind('mousemove')

in your click event.




回答3:


else if(e.type == 'click')
{
    $(window).unbind('mousemove')
}

But really you should name the event so you only unbind the appropriate event listener.

Bind : $(window).bind('mousemove.dragging', function(){});

Unbind : $(window).unbind('mousemove.dragging', function(){});



来源:https://stackoverflow.com/questions/4587632/disable-mousemove-on-click

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