How to get the direction of moving object in dragg

2019-02-15 05:24发布

问题:

I have object (div-box), and it's draggable (I'm using jQuery). How I can get information which direction a visitor moved it? Example: User drag it to left down and I wanna know it, how?

回答1:

how about this?

var start,stop;

$("#draggable2").draggable({
    axis: "x",
    start: function(event, ui) {
        start = ui.position.left;
    },
    stop: function(event, ui) {
        stop = ui.position.left;
        alert('has moved ' + ((start < stop) ? 'right':'left'))
    }
});​

crazy fiddle



回答2:

The original position is built into the ui.helper object.. You can just do:

        $('#foo').draggable({
            stop: function(event, ui) {
                var dragged = ui.helper;
                var dragged_data = dragged.data('draggable');
                var direction = (dragged_data.originalPosition.left > dragged.position().left) ? 'left' : 'right';

                console.log(direction);
            }
        });

You can do this in the start, drag, or stop event callbacks...



回答3:

There is two answers to this question:

  1. get direction in real time, namely no matter the starting position. For that you need to set and use previousPosition as follow:

    
    $("#draggable").draggable({
        axis: "x",
        start: function(event, ui) {
            this.previousPosition = ui.position;
        },
        drag: function(event, ui) {
            var direction = (this.previousPosition.left > ui.position.left) ? 'left' : 'right';
            alert('moving ' + direction)
        }
    });​
    

  2. get direction after the drop, therefore using the starting position. For that you need to use the provided originalPosition as follow:

    
    $("#draggable").draggable({
        axis: "x",
        stop: function(event, ui) {
            var direction = (ui.originalPosition.left > ui.position.left) ? 'left' : 'right';
            alert('has moved ' + direction)
        }
    });​
    

Note: This code was written for and tested with jQuery 1.11.1



回答4:

Take a look at this page, Source code and Demo is available on this website :

http://www.coursesweb.net/jquery/jquery-ui-draggable-drag