jQuery UI:从原始div拖动并克隆,但保留克隆

我有一个div,它应用了jQuery UI Draggable。 我想要做的是点击并拖动它,并创建一个保存在dom中的克隆,并在删除时不删除。

想想一副牌,我的盒子元素就是牌组,我想从牌组中拉出牌/ div并将它们放在我的页面周围,但它们将是原始div的克隆。 我只是想确保你不能创建一个克隆div的另一个克隆。

我使用了以下,但没有像我想的那样工作:

$(".box").draggable({ axis: 'y', containment: 'html', start: function(event, ui) { $(this).clone().appendTo('body'); } }); 

我想出了我的解决方案:

 $(".box-clone").live('mouseover', function() { $(this).draggable({ axis: 'y', containment: 'html' }); }); $(".box").draggable({ axis: 'y', containment: 'html', helper: 'clone' stop: function(event, ui) { $(ui.helper).clone(true).removeClass('box ui-draggable ui-draggable-dragging').addClass('box-clone').appendTo('body'); } }); 

这是我最终做的工作:

 $(".box-clone").live('mouseover', function() { $(this).draggable({ axis: 'y', containment: 'html' }); }); $(".box").draggable({ axis: 'y', containment: 'html', helper: 'clone', stop: function(event, ui) { $(ui.helper).clone(true).removeClass('box ui-draggable ui-draggable-dragging').addClass('box-clone').appendTo('body'); } }); 

如果你想将#source

    中的元素(比如

  • )移动到#destination

      ,你希望它们克隆(而不是移动),并且仍然是在右边可排序,我找到了这个解决方案:

       $(function() { $("#source li").draggable({ connectToSortable: '#destination', helper: 'clone' }) $("#destination").sortable(); }); 

      我知道它看起来很简单,但它对我有用! 🙂

      这是他的解决方案:

       $(".box-clone").live('mouseover', function() { $(this).draggable({ axis: 'y', containment: 'html' }); }); $(".box").draggable({ axis: 'y', containment: 'html', helper: 'clone' stop: function(event, ui) { $(ui.helper).clone(true).removeClass('box ui-draggable ui-draggable-dragging').addClass('box-clone').appendTo('body'); } }); 

      以下是我如何使用它:PS:’marker’是要拖动的对象,’map’是目标容器。

       $(document).ready(function() { //source flag whether the drag is on the marker tool template var template = 0; //variable index var j = 0; $(".marker").draggable({ helper: 'clone', snap: '.map', start: function(event, ui) { //set the marker tool template template = 1; } }); $(".map").droppable({ accept: ".marker", drop: function(event, ui) { $(this).find('.map').remove(); var item = $(ui.helper); var objectid = item.attr('id'); //if the drag is on the marker tool template if (template == 1) { var cloned = $(item.clone()); cloned.attr('id', 'marker' + j++); objectid = cloned.attr('id'); cloned.draggable({ containment: '.map', cursor: 'move', snap: '.map', start: function(event, ui) { //Reset the drag source flag template = 0; } }); cloned.bind("contextmenu", function(e) { cloned.remove(); return false; }); $(this).append(cloned); } i++; var offsetXPos = parseInt(ui.offset.left - $(this).offset().left); var offsetYPos = parseInt(ui.offset.top - $(this).offset().top); alert("Dragged " + objectid + " to (" + offsetXPos + "," + offsetYPos + ")"); } }); });