我如何控制不将可拖动项目放置在其他可拖动项目中?

时间:2019-11-20 22:25:55

标签: javascript jquery html drag-and-drop draggable

在以下有关HTML和JQuery的其他教程中,我创建了此拖放示例:

var dragOverHandler = function(e) {
  e.preventDefault();
};

var dropOnBoxContainerHandler = function(e) {
  e.preventDefault();
  var data = e.originalEvent.dataTransfer.getData('Text');
  e.target.appendChild(document.getElementById(data));   
  $('.dropzone').each(function() {
    if ($(this).is(':empty')) { //if the dropzone is empty we can put other box again
      $(this).on('dragover', dragOverHandler);
      $(this).on('drop', dropOnBoxContainerHandler);
    }else{
      $(this).off('dragover drop'); //if there is something in this dropzone we cant drop anything else
    }
  });
}

$(document).ready(function() {
  $('.box').on('dragstart', function(e) {
    e.originalEvent.dataTransfer.setData('Text', e.target.id);
  });
  $('.dropzone, #boxContainer').on('dragover', dragOverHandler);
  $('.dropzone').on('drop', dropOnBoxContainerHandler);
  $('#boxContainer').on('drop', dropOnBoxContainerHandler);

});
.dropzone, #boxContainer {
  border: 1px solid #000;
  height: 40px;
  margin: 5px;
  width: 200px;
}

.box {
  background: #000;
  color: #fff;
  display: inline-block;
  margin: 5px;
  padding: 5px;
  user-select: none;
}

#boxContainer {
  background-color: #AAA;
}
<script
	src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
  <div class="dropzone"></div> <!–– WHERE YOU CAN DROP ONLY ONE ELEMENT ––>
  <div class="dropzone"></div>
  <div class="dropzone"></div>
</div>
<div id="boxContainer"> <!–– the elements container to move ––>
  <div class="box" id="drag-a" draggable="true">box a</div>   
  <div class="box" id="drag-b" draggable="true">box b</div>
  <div class="box" id="drag-c" draggable="true">box c</div>
</div>

我确定只能将一个盒子同时放到每个“ dropzone”中,但是问题在于,我可以在boxcontainer中将一个“ box”放到另一个“ box”中在此图像中:

enter image description here

那我该如何解决呢?

0 个答案:

没有答案