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?
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.
Try adding
$(window).unbind('mousemove')
in your click event.
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(){});
精彩评论