在可拖动元素中奇怪的跳跃

Weird jumping in Draggable elements

本文关键字:跳跃 拖动 元素      更新时间:2023-09-26

为了好玩,我一直在尝试创建自己的可拖动div,但我遇到了一两个问题。

第一个也是最烦人的是试图允许用户从他们碰巧点击的div 中的位置拖动。这在左上角和右下角都非常有效。然而,在左下角和右上角,它们会翻转,就像你点击一个,它会跳到另一个。我似乎无法为此想出解决方案。

 function DragMe(e) {
    var relativeXPosition = (e.pageX - this.offsetLeft);
    var relativeYPosition = (e.pageY - this.offsetTop);
    $(document).on('mousemove',function(e) {
       $('.move').offset({
           top: e.pageY - relativeXPosition,
           left: e.pageX - relativeYPosition,
        });
    });
};
$('.move').on('mousedown', DragMe);
$('.move').mouseup(function() {
    $(this).off('mousedown');
    $(document).off('mousemove');
    $('.move').on('mousedown', DragMe);
});

http://jsfiddle.net/VpM9j/

这就是我到目前为止所拥有的,如果有人知道我如何开始在多个div 上完成这项工作,那将是很棒的。我之前试过,但它只是将所有div 卡在一起,所以一个会消失。

我知道这可能在jQuery UI中是可行的,但我希望现在避免这种情况,只是为了让它更具挑战性,因为我仍在学习。

答案很简单:您在回调函数中混淆了 X 和 Y

function DragMe(e) {
    var relativeXPosition = (e.pageX - this.offsetLeft);
    var relativeYPosition = (e.pageY - this.offsetTop);
    $(document).on('mousemove',function(e) {
       $('.move').offset({
           top: e.pageY - relativeYPosition, // you had relativeXPosition here
           left: e.pageX - relativeXPosition, // you had relativeYPosition here
        });
    });
};
$('.move').on('mousedown', DragMe);
$('.move').mouseup(function() { // drop the other offs and ons
    $(document).off('mousemove');
});

请参阅:http://jsfiddle.net/VpM9j/2/

回答你的第二个问题:

function DragMe(e) {
    var dragDiv = e.target;
    var relativeXPosition = (e.pageX - dragDiv.offsetLeft);
    var relativeYPosition = (e.pageY - dragDiv.offsetTop);
    $(document).on('mousemove',function(e) {
       $(dragDiv).offset({
           top: e.pageY - relativeYPosition,
           left: e.pageX - relativeXPosition,
        });
    });
};

请参阅:http://jsfiddle.net/VpM9j/4/

但更好的是事件委派,因为您只需要文档上的 1 个事件侦听器,而不是您拥有的那么多div:

function DragMe(e) {
    var dragDiv = this; // <-- pay attention to that ;o)
    var relativeXPosition = (e.pageX - this.offsetLeft);
    var relativeYPosition = (e.pageY - this.offsetTop);
    $(document).on('mousemove',function(e) {
       $(dragDiv).offset({
           top: e.pageY - relativeYPosition,
           left: e.pageX - relativeXPosition,
        });
    });
};
$(document).on('mousedown', '.move', DragMe);
$(document).on('mouseup', '.move', function() {
    $(document).off('mousemove');
});

请参阅:http://jsfiddle.net/VpM9j/7/

有关事件委派的详细信息,请参阅:http://api.jquery.com/on/,然后搜索"直接和委派事件"