复制原始元素而不删除使用Jquery拖放

时间:2012-10-08 20:37:13

标签: jquery drag-and-drop clone

我有一个小部件,我可以将项目放入容器中。我希望能够将原始元素保留在droppable容器之外,以便用户可以将相同的元素拖放到容器中(因此容器可以具有多个相同的元素)。我正在使用克隆助手,但无法弄清楚如何不删除原始元素。任何帮助表示赞赏。谢谢!以下是我的代码:

$(function() {
var $gallery = $( "#gallery" ),
    $trash = $( "#trash" );


$( "li", $gallery ).draggable({
    cancel: "a.ui-icon", 
    revert: "invalid", 
    containment: $( "#demo-frame" ).length ? "#demo-frame" : "document", // stick to demo-frame if present
    helper: "clone",
    cursor: "move"
});


$trash.droppable({
    accept: "#gallery > li",
    activeClass: "ui-state-highlight",
    drop: function( event, ui ) {
        deleteImage( ui.draggable );
    }
});

$gallery.droppable({
    accept: "#trash li",
    activeClass: "custom-state-active",
    drop: function( event, ui ) {
        recycleImage( ui.draggable );
    }
});

HTML:

<div class="demo ui-widget ui-helper-clearfix">

<ul id="gallery" class="gallery ui-helper-reset ui-helper-clearfix">
    <li class="ui-widget-content ui-corner-tr" a href="link/to/trash/script/when/we/have/js/off">
        <h5 class="fpheader">Red</h5>   

    </li>
    <li class="ui-widget-content ui-corner-tr">
        <h5 class="fpheader">Orange</h5>

    </li>
    <li class="ui-widget-content ui-corner-tr">
        <h5 class="fpheader"Yellow</h5>
    </li>
    <li class="ui-widget-content ui-corner-tr">
        <h5 class="fpheader">Green</h5>
    </li>
    <li class="ui-widget-content ui-corner-tr">
        <h5 class="fpheaderr">Blue</h5>
    </li>
    <li class="ui-widget-content ui-corner-tr">
        <h5 class="fpheader">Purple</h5>
    </li>
    <li class="ui-widget-content ui-corner-tr">
        <h5 class="fpheader">White</h5>

    </li>
</ul>

</div>

1 个答案:

答案 0 :(得分:1)

克隆助手克隆您拖动的元素,以便在拖动时显示。否则它不会在drop上克隆元素。你需要在drop处理程序中做的是自己克隆元素(你可以使用ui.draggable)并将它附加到你的droppable容器。

以下是一个例子:

$trash.droppable({
    accept: "#gallery > li",
    activeClass: "ui-state-highlight",
    drop: function( event, ui ) {
        var element = ui.draggable.clone().appendTo($(this));
        element.draggable({
            cancel: "a.ui-icon", 
            revert: "invalid", 
            containment: $( "#demo-frame" ).length ? "#demo-frame" : "document", // stick to demo-frame if present
            helper: "clone",
            cursor: "move"
        });
    }
});