0

For fun I have been trying to create my own dragable divs and I have run into an issue or two.

The first and most annoying one is trying to allow the user to drag from where ever in the div they happen to click. This works great on both top left and bottom right. However on bottom left and top right they flip flop, as in you click one and it jumps to the other. I cannot seem to come up with a solution for this.

 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/

This is what I have so far, also if anyone knows how I might get started on making this work on multiple divs that would be awesome. I tried before but it just snapped all the divs together and so one would disappear.

I understand this is probably do-able with jQuery UI but I was hoping to avoid that for now just to make it a bit more challenging since I'm still learning.

4

1 回答 1

1

答案很简单:你在回调函数中混淆了 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/并搜索“直接和委托事件”

于 2013-10-01T17:17:26.127 回答