How to find out about the “snapped to” element for jQuery UI draggable elements on snap

女生的网名这么多〃 提交于 2019-12-17 11:44:15

问题


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.

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.

Any suggestions? Thanks!


回答1:


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

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

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 
    }, ...
]

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! */
    }
});

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.

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

Hope that helps.



来源:https://stackoverflow.com/questions/5177867/how-to-find-out-about-the-snapped-to-element-for-jquery-ui-draggable-elements

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!