Javascript drag and drop multiple instances of the same object

跟風遠走 提交于 2019-12-22 14:48:07

问题


I want to develop a javascript drag and drop application just like the one you can see here , where you can pick and object and drag it to another area. But i want to do this with a twist. I want to be able do drag the same object multiple time, instead of moving the object from the book shelf to the basket, i want to drag one instance of the object to the book shelf and still have the object on the book shelf.

It's like buying multiple instances of the same object, each time i drag the object from the book shelf to the basket, i add another instance of the object to the basket.

Any ideas on how can i achieve this effect?


回答1:


You do the same thing as with regular drag and drop but instead of removing the dragged object, you clone it.

Implementing drag and drop is kind of tricky, a library like jQuery could really save you a lot of time and effort. jQuery UI's draggable has a helper: clone option which leaves the dragged object in place, cloning it instead. Then when defining your drop area using jQuery UI Droppable you can do whatever you want with the dropped element, like creating a new element representing the basket item, leaving the dragged item untouched. So if using jQuery is an option, that wouldn't be difficult to do at all.

UPDATE: HERE'S A QUICK DEMO

HTML

<div id="list">
    <div class="productItem">product 1</div>
    <div class="productItem">product 2</div>
    <div class="productItem">product 3</div>
</div>

<div id="basket">
</div>​

JS

$(".productItem").draggable({
    helper: 'clone',
    handle: "productItem"
});

$("#basket").droppable({
    accept: ".productItem",
    drop: function(event, ui){
        $("<div></div>")
            .html(ui.draggable.text())
            .appendTo($(this));
    }
});



来源:https://stackoverflow.com/questions/12462451/javascript-drag-and-drop-multiple-instances-of-the-same-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!