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

后端 未结 1 1287
野趣味
野趣味 2020-12-03 08:01

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,

相关标签:
1条回答
  • 2020-12-03 08:27

    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.

    0 讨论(0)
提交回复
热议问题