Clone draggable after dropping in targeted area wi

2019-05-13 12:15发布

I want some images to drop in a targeted area as many times as possible. But the image drops for only one time. My jQuery UI code:

 $(function() {
    $( ".draggable img").draggable({ 
        revert: "invalid",
        appendTo: "#droppable",
        helper: "clone" 
    });
    $( "#droppable" ).droppable({
        activeClass: "ui-state-default",
        hoverClass: "ui-state-hover",
        drop: function( event, ui ) {
           $( this ).find( ".placeholder" ).remove();
           var image = $(".ui-draggable");
           $( "<img />" ).image.src.appendTo( this );
        }
    });
});

Please see the demonstration here: jsFiddle example

From the example you see that the image drops in the div area only the first time. But I want the user to have the ability to drag and drop the same image as many times as they want in the targeted area.

So for example a user can drag and drop the image 5 times and there will be 5 images cloned in the targeted area. How can I do that?

1条回答
等我变得足够好
2楼-- · 2019-05-13 12:48

You were almost there. You need the helper: "clone" attribute indeed. The best way to do this is to create a new clone when the drop event fires using .clone(). Then just initialise it and you're done:

$(function() {
    $(".draggable img").draggable({ 
        revert: "invalid",
        helper: "clone" 
    });   
    $("#droppable").droppable({
        activeClass: "ui-state-default",
        hoverClass: "ui-state-hover",
        drop: function(event, ui) {
            var newClone = $(ui.helper).clone();
            $(this).after(newClone);
        }
    });
});

DEMO

As a comment: I highly recommmend the method I described above as it is better to make the clone in the drop event of the droppable then to bind a dragstop event to the draggable. This because otherwise too many clones will be made: my code ensures that no redundant clones are produced. To see what I mean, open this jsFiddle (which uses the wrong method: cloning on dragstop) and try dropping the draggable outside of the designated area. What happens is that redundant clones will be added to the DOM. This is both inefficient and ugly and should be avoided.

查看更多
登录 后发表回答