简体   繁体   中英

jQuery UI Draggable Snapping into a Container

Description of Problem ( Fiddle ):

Using jQuery UI's .draggable() function, I'm trying to make the red element snap to the inside of the blue container. It's snapping first to one edge rather than completely inside it (ie to both edges). You must continue dragging it until it snaps to the other axis.

When it begins to snap at any angle, I want it to go to its final position (fully inside the container). Is there a way to detect when a snap begins (ie the event is fired) and then use that to manually reposition the red box?

Example Code:

HTML:

<div id="box"></div>
<div id="container"></div>

JavaScript:

$('#box').draggable({
    snap: '#container',
    snapMode: 'inner',
    snapTolerance: 50
});

CSS:

#box {
    background: red;
    width: 100px;
    height: 100px;
    position: absolute;
    z-index: 1;
}
#container {
    width: 102px;
    height: 102px;
    position: absolute;
    top: 50%;
    left: 50%;
    margin-top: -51px;
    margin-left: -51px;
    border: 1px solid blue;
}

Fiddle: http://jsfiddle.net/W8yaz/9/

Snap event help: Jquery UI – draggable 'snap' event

Right now, after snapping there is no more draggin possible. This will be another headache.

Beside note: you can't trigger mouseup to cancel the drag event, this is causing a known javascript error, can be seen in a previous fiddle: http://jsfiddle.net/W8yaz/7/

JavaScript:

$('#box').draggable({
    snap: '#container',
    snapMode: 'inner',
    snapTolerance: 50,
    drag: function (event, ui) {
        if ($(this).hasClass('snapped')) {
            var position = $('#container').position();

            $(this).css({
                top: position.top,
                left: position.left
            });
            return false;
        } else {
            var draggable = $(this).data("uiDraggable");
            $.each(draggable.snapElements, function (index, element) {
                if (element.snapping) {
                    draggable._trigger("snapped", event, $.extend({}, ui, {
                        snapElement: $(element.item)
                    }));
                }
            });
        }
    },
    snapped: function (event, ui) {
        $(this).addClass('snapped');
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM