我正在尝试拖放一些项目。我可以将一个div拖到拖放区div上,并且效果很好。但是,当我拖动另一个div时,实际上可以将其放到先前放置的div中。我不想这样。我希望放置区域是唯一可以接受放置div的地方。
<div class='container-fluid'>
<div class='row'>
<div class='col-sm-12' style='padding:0px;'>
<div class='col-sm-6'>
<div class='row'>
<div class='col-sm-2 drag-example' id='drag-1'
draggable='true' ondragstart='drag(event)'></div>
<div class='col-sm-2 drag-example' id='drag-2'
draggable='true' ondragstart='drag(event)'></div>
<div class='col-sm-2 drag-example' id='drag-3'
draggable='true' ondragstart='drag(event)'></div>
</div>
</div>
<div class='col-sm-6'>
<div class='row'>
<div class='col-sm-10 drop-example'
ondrop='drop(event)' ondragover='allowDrop(event)'
id='drop-div'></div>
</div>
</div>
</div>
</div>
</div>
function allowDrop(ev){
ev.preventDefault();
}
function drag(ev){
ev.dataTransfer.setData('text', ev.target.id);
}
function drop(ev){
ev.preventDefault();
var data = ev.dataTransfer.getData('text');
ev.target.appendChild(document.getElementById(data).cloneNode(true));
}
答案 0 :(得分:0)
this
引用作为第二个参数
function allowDrop(ev) {
ev.preventDefault();
}
function drag(ev) {
ev.dataTransfer.setData("text", ev.target.id);
}
// change 1 :: added el
function drop(ev, el) {
ev.preventDefault();
var data = ev.dataTransfer.getData("text");
// change 2 :: append to el
el.appendChild(document.getElementById(data).cloneNode(true));
}
.drag-example {
border: 1px Solid Black;
width: 50px;
height: 50px;
margin-bottom: 5px;
}
.drop-example {
border: 1px Solid Red;
width: 50px;
height: 50px;
}
<div class='drag-example' id='drag-1' draggable='true' ondragstart='drag(event)'></div>
<!-- change 3 :: pass this to drop -->
<div class='drop-example' ondrop='drop(event, this)' ondragover='allowDrop(event)' id='drop-div'></div>