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:
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) } });
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