开发者

cancelling jquery draggable objects or reset

开发者 https://www.devze.com 2023-03-17 04:20 出处:网络
i would开发者_StackOverflow社区 like to load a page of objects that can be dragged on to a map/div but would like to have a clear/undo button? is this possible with jquery?

i would开发者_StackOverflow社区 like to load a page of objects that can be dragged on to a map/div but would like to have a clear/undo button? is this possible with jquery?

you can see code in a previous question

jQuery UI droppables - changing the image that's dropped


This is possible with a simple call to .animate() (which, after all, is all jQueryUI is doing) and some logic to keep track of the original position of the element you're dragging (which jQueryUI already partially handles for you).

  1. Keep track of the original position of your draggable elements using .data() and the .drop() event of your droppable object:

    $("#drop").droppable({
        drop: function(event, ui) {
            if (!ui.draggable.data("originalPosition")) {
                ui.draggable.data("originalPosition",
                    ui.draggable.data("draggable").originalPosition);
            }
        }
    });
    

    Basically this just sets data called "originalPosition" on the dragged element. This assumes that you're able to keep dragging the element inside a valid drop zone (and so it doesn't overwrite the original position after you keep dragging).

  2. Create a function that you call that animates the dragged object back to its original position:

    function revertDraggable($selector) {
        $selector.each(function() {
            var $this = $(this),
                position = $this.data("originalPosition");
    
            if (position) {
                $this.animate({
                    left: position.left,
                    top: position.top
                }, 500, function() {
                    $this.data("originalPosition", null);
                });
            }
        });
    }
    

    Adjust the speed of the animation to your liking.

  3. Call that function from an event handler:

    $("#undo").click(function() {
        revertDraggable($(".drag"));
    });
    

Here's a working example: http://jsfiddle.net/v7N6w/

0

精彩评论

暂无评论...
验证码 换一张
取 消