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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 04:05:57  来源:igfitidea点击:

detect when item is being dragged left or right with jQuery UI's draggable?

javascriptjqueryjquery-ui

提问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');
    }
});

Demo: http://jsfiddle.net/GNHTW/

演示:http: //jsfiddle.net/GNHTW/

回答by basarat

I would recommend you handle the startand stopevents and determine the position delta in stop event to get whether it was moved left or right:

我建议您处理startstop事件并确定停止事件中的位置增量以获取它是向左移动还是向右移动:

http://jqueryui.com/draggable/#events

http://jqueryui.com/draggable/#events