使用jQuery UI放到目标区域后克隆可拖动 [英] Clone draggable after dropping in targeted area with jQuery UI

查看:369
本文介绍了使用jQuery UI放到目标区域后克隆可拖动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望一些图像尽可能多地放在目标区域中.但是图像仅下降一次.我的jQuery UI代码:

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 );
        }
    });
});

请在此处查看演示: jsFiddle示例

Please see the demonstration here: jsFiddle example

从示例中您可以看到,图像仅在第一次落入div区域.但是我希望用户能够在目标区域中任意拖放同一张图像 次.

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.

例如,用户可以将图像拖放5次,在目标区域中将有5张图像被克隆.我该怎么办?

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?

推荐答案

您快到了.您确实需要helper: "clone"属性.最好的方法是使用 .clone() .然后将其初始化即可完成:

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);
        }
    });
});

演示

作为评论:我强烈建议使用上述方法,因为最好在droppabledrop事件中进行克隆,然后将dragstop事件绑定到draggable .这是因为否则将进行过多的克隆:我的代码确保不会产生多余的克隆.要了解我的意思,请打开 此jsFiddle (使用错误的方法:在拖放控件上克隆),然后尝试将可拖动的拖放到指定区域之外.发生的事情是多余的克隆将被添加到DOM.这既低效又丑陋,应该避免.

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.

这篇关于使用jQuery UI放到目标区域后克隆可拖动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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