取消jQuery可拖动对象或重置 [英] cancelling jquery draggable objects or reset

查看:61
本文介绍了取消jQuery可拖动对象或重置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想加载可以拖到地图/div上的对象页面,但想要一个清除/撤消按钮吗? jQuery有可能吗?

i would 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-更改被丢弃的图像

推荐答案

可以通过对.animate()的简单调用(毕竟,这是jQueryUI的全部工作)以及一些跟踪原始位置的逻辑来实现的拖动的元素(jQueryUI已经部分为您处理).

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. 使用.data()droppable对象的.drop()事件跟踪可拖动元素的原始位置:

  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);
        }
    }
});

基本上,这只是在拖动的元素上设置了称为"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).

创建一个调用函数,将拖动的对象动画化回其原始位置:

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.

从事件处理程序中调用该函数:

Call that function from an event handler:

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

这是一个工作示例: http://jsfiddle.net/v7N6w/

这篇关于取消jQuery可拖动对象或重置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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