如何使 div 可拖放

how to make a div draggable and droppable

我的项目中剩下的一件事是让两个 div 同时可拖放。现在我有了可以拖放的 divs 的工作代码,但是例如我可以从目标区域拖动 div 并将其放到用户区域,但我似乎无法找到一种方法来从用户中拖出 div 并分配给不同的用户。

$(document).ready(function(){
    $(".dragable").draggable({
        cancel: "a.ui-icon",
        revert: true,
        helper: "clone",
        cursor: "move",
        revertDuration: 0
    });

    $('.droppable').droppable({
        accept: ".dragable",
        activeClass: "ui-state-highlight",
        drop: function( event, ui ) {
            // clone item to retain in original "list"
            var $item = ui.draggable.clone();
            $(this).addClass('has-drop').append($item);
        }
    });
});

http://jsfiddle.net/coder880/TpbZk/31/

问题是因为项目一旦 dragged/dropped 就会被克隆。此克隆没有实例化 draggable() 插件。您需要再次在 $item 上调用 draggable()。试试这个:

var draggableOptions = {
    cancel: "a.ui-icon",
    revert: true,
    helper: "clone",
    cursor: "move",
    revertDuration: 0
}

$(".dragable").draggable(draggableOptions);

$('.droppable').droppable({
    accept: ".dragable",
    activeClass: "ui-state-highlight",
    drop: function(event, ui) {
        var $item = ui.draggable.clone();
        $item.draggable(draggableOptions);
        $(this).addClass('has-drop').append($item);
    }
});

Updated fiddle

it should only be cloned when its from target otherwise it should move it.

为此,您需要删除克隆的可拖动元素中的 helper: 'clone' 选项,并在该元素上保留一个标志,以确定它是全新的克隆还是之前已被拖动并再次移动。为此,您可以使用 class,如下所示:

$(".dragable").draggable({
    cancel: "a.ui-icon",
    revert: true,
    helper: "clone",
    cursor: "move",
    revertDuration: 0
});

$('.droppable').droppable({
    accept: ".dragable",
    activeClass: "ui-state-highlight",
    drop: function(event, ui) {
        var $item = $(ui.draggable)
        if (!$item.hasClass('clone')) {
            $item = $item.clone().addClass('clone');
            $item.draggable({
                cancel: "a.ui-icon",
                revert: true,
                cursor: "move",
                revertDuration: 0
            });
        }
        $(this).addClass('has-drop').append($item);
    }
});

Example fiddle