【问题标题】:JQuery draggable() clone and then moveJQuery draggable() clone and then move
【发布时间】:2022-11-20 20:25:42
【问题描述】:

I want to drag a clone of an object with the classname "draggable" into a dropzone and then also be able to move the new object within the dropzone.

This is what I have done so far and it allmost works, but it also makes a clone when I move the object within the dropzone. How can I avoid this?

.draggable{
    width: 100px;
    height: 100px;
    background-color: lightblue;
}
#dropZone{
    width:300px;
    height:300px;
    background:yellow;
    position:relative;
}
<script src="https://code.jquery.com/jquery-3.6.0.js"></script>
<script src="https://code.jquery.com/ui/1.13.2/jquery-ui.js"></script>

<script>
$(document).ready(function(){
    $( ".draggable" ).draggable({
        helper:"clone"
    });

    $( "#dropZone" ).droppable({
        accept: '.draggable',
        drop: function(event, ui){
            var obj = ui.draggable.clone();
            $(this).append(obj);
            obj.draggable({disabled: false})
        }

    });

});
</script>    


<div id="dropZone" ></div>
<div class="draggable ui-widget-content">Drag me</div>

【问题讨论】:

    标签: jquery drag-and-drop jquery-ui-draggable


    【解决方案1】:

    Drop event occurs repeatedly, whether you're dragging elements from outside or inside the container. So check whether an droppable element is already inside the container, if so, do not add it to the container:

    Example:

    $(".draggable").draggable({
      helper: "clone"
    });
    
    $("#dropZone").droppable({
      accept: '.draggable',
      drop: function(event, ui) {
        var obj = ui.draggable.clone();
        if (!obj.is('.inside-drop-zone')) {
          $(this).append(obj.addClass('inside-drop-zone').draggable({
            containment: '#drop-zone'
          }));
        }
      }
    
    });
    .draggable {
      width: 100px;
      height: 100px;
      background-color: lightblue;
    }
    
    #dropZone {
      width: 300px;
      height: 300px;
      background: yellow;
      position: relative;
    }
    <script src="https://code.jquery.com/jquery-3.6.0.js"></script>
    <script src="https://code.jquery.com/ui/1.13.2/jquery-ui.js"></script>
    
    <div id="dropZone"></div>
    <div class="draggable ui-widget-content">Drag me</div>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-02-25
      • 2012-04-28
      • 1970-01-01
      • 2014-01-28
      • 1970-01-01
      • 2011-04-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多