在发生droppable事件时,将jQuery可拖动对象恢复为其原始容器 [英] Revert a jQuery draggable object back to its original container on out event of droppable

查看:82
本文介绍了在发生droppable事件时,将jQuery可拖动对象恢复为其原始容器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个可拖动物品,如果没有放置在可放置物品中,它将还原.直到用户将项目放置到可放置对象中之前,此方法都可以正常工作.如果他们确定他们在任何时候都犯了一个错误,则将可拖动对象拖出,它会恢复为可放置对象.我希望先退出并停用可拖动对象,再返回其原始容器.

I have a draggable item which if not dropped in a droppable will revert. This works well until a user drops an item in the droppable. If they decide they've made a mistake anytime they pull the draggable out it reverts to the droppable. I would prefer that on out and deactivate the draggable goes back to its original container.

我的代码在下面,但是我提供了关于jsFiddle的示例.

My code is below but I have provided a sample on jsFiddle.

HTML

<div id="origin">
    <div id="draggable" class="ui-widget-content">
        <p>I revert when I'm not dropped</p>
    </div>
</div>
<div id="droppable" class="ui-widget-header">
    <p>Drop me here</p>
</div>

JavaScript

JavaScript

$(function() {
    $("#draggable").draggable({ 
        revert:  function(dropped) {
           var dropped = dropped && dropped[0].id == "droppable";
           if(!dropped) alert("I'm reverting!");
           return !dropped;
        } 
    }).each(function() {
        var top = $(this).position().top;
        var left = $(this).position().left;
        $(this).data('orgTop', top);
        $(this).data('orgLeft', left);
    });

    $("#droppable").droppable({
        activeClass: 'ui-state-hover',
        hoverClass: 'ui-state-active',
        drop: function(event, ui) {
            $(this).addClass('ui-state-highlight').find('p').html('Dropped!');
        },
        out: function(event, ui) {
                // doesn't work but something like this
                ui.draggable.mouseup(function () {
                var top = ui.draggable.data('orgTop');
                var left = ui.draggable.data('orgLeft');
                ui.position = { top: top, left: left };
            });
        }
    });
});

推荐答案

  • 已测试,带有 jquery 1.11.3 & jquery-ui 1.11.4

  • TESTED with jquery 1.11.3 & jquery-ui 1.11.4

演示::

$(function() {
    $("#draggable").draggable({
        revert : function(event, ui) {
            // on older version of jQuery use "draggable"
            // $(this).data("draggable")
            // on 2.x versions of jQuery use "ui-draggable"
            // $(this).data("ui-draggable")
            $(this).data("uiDraggable").originalPosition = {
                top : 0,
                left : 0
            };
            // return boolean
            return !event;
            // that evaluate like this:
            // return event !== false ? false : true;
        }
    });
    $("#droppable").droppable();
});

这篇关于在发生droppable事件时,将jQuery可拖动对象恢复为其原始容器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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