javascript 使用 jQuery UI 的可拖动检测何时向左或向右拖动项目?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16293451/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
detect when item is being dragged left or right with jQuery UI's draggable?
提问by Irfan Mir
I am using JQuery UI to make an element draggable and in the code, one can specify what to do on start, drag, and end.
我正在使用 JQuery UI 使元素可拖动,并且在代码中,可以指定在开始、拖动和结束时要执行的操作。
But how can I run one function on drag left and another on drag right?
但是如何在向左拖动时运行一个功能而在向右拖动时运行另一个功能?
I have already limited the draggable axis to the x-axis only. So the element can only move left or right.
我已经将可拖动轴限制为仅 x 轴。所以元素只能向左或向右移动。
回答by techfoobar
Check this demo: http://jsfiddle.net/3NtS9/
检查这个演示:http: //jsfiddle.net/3NtS9/
You can do it by checking against the previous event coordinate on each atomic drag operation.
您可以通过检查每个原子拖动操作上的前一个事件坐标来实现。
var prevX = -1;
$('div').draggable({
drag: function(e) {
//console.log(e.pageX);
if(prevX == -1) {
prevX = e.pageX;
return false;
}
// dragged left
if(prevX > e.pageX) {
console.log('dragged left');
}
else if(prevX < e.pageX) { // dragged right
console.log('dragged right');
}
prevX = e.pageX;
}
});
回答by Ayman Safadi
Here's an easier way to do it:
这是一个更简单的方法:
$( "#draggable" ).draggable({
drag: function( event, ui ) {
$(this).text(ui.originalPosition.left > ui.position.left ? 'left' : 'right');
}
});
回答by basarat
I would recommend you handle the start
and stop
events and determine the position delta in stop event to get whether it was moved left or right:
我建议您处理start
和stop
事件并确定停止事件中的位置增量以获取它是向左移动还是向右移动: