有两个问题.一个是你在鼠标离开元素时取消拖动,你不想这样做.第二个是mousemove只是在盒子上,一旦光标开箱即可,不再执行mousemove.您可以存储要拖动的元素,然后将mousemove添加到整个页面.
编辑:实际上,我猜想mouseup应该也是在文件上,以防万一你在快速移动时释放鼠标点击,光标在框外.更新了jsfiddle.
看这里:
var box = $('#box');
box.offset({
left: 100,top: 75
});
var drag = {
elem: null,x: 0,y: 0,state: false
};
var delta = {
x: 0,y: 0
};
box.mousedown(function(e) {
if (!drag.state) {
drag.elem = this;
this.style.backgroundColor = '#f00';
drag.x = e.pageX;
drag.y = e.pageY;
drag.state = true;
}
return false;
});
$(document).mousemove(function(e) {
if (drag.state) {
drag.elem.style.backgroundColor = '#f0f';
delta.x = e.pageX - drag.x;
delta.y = e.pageY - drag.y;
$('#log').text(e.pageX + ' ' + e.pageY + ' ' + delta.x + ' ' + delta.y);
var cur_offset = $(drag.elem).offset();
$(drag.elem).offset({
left: (cur_offset.left + delta.x),top: (cur_offset.top + delta.y)
});
drag.x = e.pageX;
drag.y = e.pageY;
}
});
$(document).mouseup(function() {
if (drag.state) {
drag.elem.style.backgroundColor = '#808';
drag.state = false;
}
});
css鼠标拖拉卡顿_在jQuery中拖动Div – 当鼠标缓慢时就很好 但是在鼠标移动快的时候会失败...