如何找出有关“被抢购"的商品的信息. jQuery UI可拖动元素的元素 [英] How to find out about the "snapped to" element for jQuery UI draggable elements on snap

查看:85
本文介绍了如何找出有关“被抢购"的商品的信息. jQuery UI可拖动元素的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理一些应该拖动到其他元素的可拖动元素,这些元素都具有类,例如".classes"和唯一的ID "#class_id".一旦将可拖动元素完成拖动,我想找出可拖动元素已捕捉到的那些".class"中.

I'm working a few draggable elements that should be snapping to other elements, which all have classes, something like, ".classes" and also a unique id, "#class_id". Once the draggable elements are done being dragged, I would like to find out which of those ".classes" that the draggable element has snapped to.

我想我可以根据被拖动元素的当前位置来计算最接近的元素,但是我觉得应该有一种比蛮力更简单的方法,因为jQuery必须保留某种变量以确保捕捉工作.

I suppose I could compute the closest element based on the current position of the dragged element, but I feel there should be an easier way than brute force, since jQuery would have to keep some sort of variable to make sure the snapping works.

有什么建议吗?谢谢!

推荐答案

jQueryUI 确实保留"snapped"元素的内部状态",但是您需要付出一些努力才能理解它.

jQueryUI does keep an internal "state" of "snapped" elements, but you have to work a little to get at it.

您将要为 stop 事件(当可拖动对象停止拖动时调用).

You're going to want to define an event handler for the stop event (which is called when a draggable object is stopped dragging).

在小部件数据中维护着一个名为snapElements的数组,它看起来像这样:

An array called snapElements is maintained inside the widget data, and it looks something like this:

[ 
    { 
        height: 102, 
        item: { /* DOM element */ }, 
        left: 10, 
        snapping: false, 
        top: 10, 
        width: 102 
    }, ...
]

我们真正关心的是itemsnapping属性. snapping会告诉我们该项目当前是否正在捕捉"到可拖动对象.

What we really care about here is the item and snapping properties. snapping will tell us if the item is currently "snapping" to a draggable object.

牢记这个数组,我们可以编写这样的代码来确定当前正在捕捉"的可捕捉目标:

With this array in mind, we can write code like this to determine the snappable targets that are currently "snapping":

$(".draggable").draggable({
    snap: ".snap",
    stop: function(event, ui) {
        /* Get the possible snap targets: */
        var snapped = $(this).data('draggable').snapElements;

        /* Pull out only the snap targets that are "snapping": */
        var snappedTo = $.map(snapped, function(element) {
            return element.snapping ? element.item : null;
        });

        /* Process the results in the snappedTo array! */
    }
});

最终结果是数组而不是单个DOM元素的原因是,当您将draggable捕捉到两个可捕捉"元素时,jQueryUI实际上足够聪明.

The reason that your end result is an array and not a single DOM element is that jQueryUI is actually smart enough to realize when you've snapped a draggable to two "snappable" elements.

以下是一个工作示例,展示了所有这些操作: http://jsfiddle.net/andrewwhitaker /uYpnW/5/

Here's a working example that shows all of this in action: http://jsfiddle.net/andrewwhitaker/uYpnW/5/

希望有帮助.

这篇关于如何找出有关“被抢购"的商品的信息. jQuery UI可拖动元素的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆