Drop a sortable into a sortable (nested divs)

2019-06-12 17:02发布

问题:

I've created a code which allows me to drag and clone divs from column 1 to column 2. The column 2 is sortable.

This works well, but I now want to drag a div from column 1 into a div which has already been dropped into column 2.

Here's my code so far:

HTML

<div id="column1">
    <p>Items</p>
    <div class="dragItem">Drag me ONE</div>
    <div class="dragItem">Drag me TWO</div>
    <div class="dragItem">Drag me THREE</div>
</div>
<div id="column2" class="droppable">
    <p>Drop here</p>
</div>

jQuery:

$('.dragItem').draggable({
    helper: 'clone',
    connectToSortable: "#column2"
});

$('.dragItem').sortable({
    containment: "parent"
});

$('#column2').sortable({
    cancel: '#cont>div',
    placeholder: "highlight"
});

$('#column2').droppable({
    accept: '.dragItem',
    drop: function(event, ui) {
        var draggable = ui.draggable;
        var droppable = $(this);
        var drag = $('#column2').has(ui.draggable).length ? draggable : draggable.clone().draggable({});
        drag.appendTo(column2); 
    }
});

Thanks

回答1:

Once the item was dropped - you need to apply the sortable and droppable to that div.

Here is an example:

$('.dragItem').draggable({
  helper: 'clone',
  connectToSortable: "#column2,#column2 div"
});

$('.dragItem').sortable({
  containment: "parent"
});

$('#column2').sortable({
  placeholder: "highlight"
});

$('#column2').droppable({
  accept: '.dragItem',
  drop: function(event, ui) {
    var draggable = ui.draggable;
    var droppable = $(this);
    var drag = $('#column2').has(ui.draggable).length ? draggable : draggable.clone().draggable({});
    drag.appendTo(column2); 
    drag.sortable({
      placeholder: "highlight"
    });
    drag.droppable({
      accept: ".dragItem",
      drop: function (event, ui) {
        var draggable = ui.draggable;
        var droppable = $(this);
        var drag = $('#column2').has(ui.draggable).length ? draggable : draggable.clone().draggable({});
      }
    })
    drag.css({width:'', height: ''})
  }
});
#column1, #column2 {
  width: 250px;
  margin-right: 10px;
  border: 1px solid red;
  float: left
}
.droppable div {
  border: 1px solid blue;
  margin: 5px;
  padding: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.0/jquery-ui.min.js"></script>
<link rel="stylesheet" type="text/css" media="screen" href="https://code.jquery.com/ui/1.12.0/themes/base/jquery-ui.css" />
<div id="column1">
  <p>Items</p>
  <div class="dragItem">Drag me ONE</div>
  <div class="dragItem">Drag me TWO</div>
  <div class="dragItem">Drag me THREE</div>
</div>
<div id="column2" class="droppable">
  <p>Drop here</p>
</div>