2017-06-02 72 views
0

如何克隆拖曳的元素并使原始元素保留在其原始位置。我想要克隆下面div中的“元素”这个词,然后我希望克隆有能力在黑色边框的框中追加,如果它落在它上面。这里是我的代码: -如何克隆jqueryUI中的拖曳元素

$(window).load(function(){ 
 

 

 
$('.me').draggable({ 
 
       helper:"clone", 
 
       containment:"document" 
 
}); 
 

 
$('#a').droppable({ 
 
     greedy: true, 
 
     drop:function(event, ui) { 
 
      ui.draggable.detach().appendTo($(this)); 
 
     } 
 
}); 
 

 
});
#a{ 
 
    height: 100px; 
 
    width:100px; 
 
    border:2px solid black; 
 
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> 
 
<script src="https://code.jquery.com/ui/1.11.3/jquery-ui.min.js"></script> 
 

 

 

 

 

 
    
 
<span class="me">element</span> 
 

 

 

 

 
    <div id="a"></div> 
 
    
 

我真的很感谢你的帮助。

+0

使用“clone()”而不是“detach()”?或者我错了吗? – Kevkong

回答

1

您可以克隆上dragstop事件的元素

编辑

正如在他的评论中使用clone代替detachdrop事件所建议的Kevkong,只是实现这个

$(window).load(function(){ 
 

 

 
    $('.me').draggable({ 
 
        helper:"clone", 
 
        containment:"document" 
 
    }); 
 

 
    $('#a').droppable({ 
 
      greedy: true, 
 
      drop:function(event, ui) { 
 
       ui.draggable.clone().appendTo($(this)); 
 
       ui.helper.data('dropped', true); 
 
      } 
 
    }); 
 
    
 
    });
#a{ 
 
    height: 100px; 
 
    width:100px; 
 
    border:2px solid black; 
 
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> 
 
<script src="https://code.jquery.com/ui/1.11.3/jquery-ui.min.js"></script> 
 
    
 
    
 
<span class="me">element</span> 
 
    
 
<div id="a"></div>

+0

非常感谢你。它可以工作,但有一个问题,元素在盒子中时会继续克隆。我该如何解决这个问题。对不起,我对jqueryui感到困惑。 –

+0

是的。我现在更新 – XYZ

+1

@Axmednuur更新了我的答案。请检查 – XYZ