单击时禁用鼠标移动
我正在尝试拖放’n’,这是我的代码:
$('.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 }); } });
在mousedown上,它应该通过移动鼠标启动拖动效果,之后如果我想停靠/放下我想要它的盒子,我点击它应该禁用移动但是如果我点击它,它不会停止移动 – 只是一直跟着我的鼠标。 你怎么能阻止拖拽?
您需要取消绑定当前仍附加的mousemove
处理程序,例如:
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); } });
或者,在jQuery 1.4.3+中, .live()
处理程序可以更清洁:
$('.box-title').live({ mousedown: function() { $(window).mousemove(setPos); }, click: function() { $(window).unbind('mousemove', setPos); } });
$(this).parent('#box')
, 看起来你在页面id="box"
有多个id="box"
元素…确保在这些情况下使用类,在这段代码中$(this).parent('#box')
将是$(this).closest('.box')
代替。
尝试添加
$(window).unbind('mousemove')
在您的点击事件中。
else if(e.type == 'click') { $(window).unbind('mousemove') }
但实际上你应该为事件命名,这样你才能解除绑定适当的事件监听器。
绑定: $(window).bind('mousemove.dragging', function(){});
$(window).unbind('mousemove.dragging', function(){});
: $(window).unbind('mousemove.dragging', function(){});