我尝试拥有2个可拖动的图像和2个目标位置,但我希望image1只能在location1中删除,而image2只能在location2中删除,此代码允许任一图像被丢弃在任何一个地方。
(为了简单起见,我省略了doctype,head,body标签等)
CSS
#div1 {width:350px;height:70px;padding:10px;border:1px solid #aaaaaa;}
#div2 {width:350px;height:70px;padding:10px;border:1px solid #aaaaaa;}
HTML
<script>
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));
}
</script>
<div id="div1" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
<img id="drag1" src="images/excercises/image1.jpg" draggable="true"
ondragstart="drag(event)" width="336" height="69">
<div id="div2" ondrop="drop(event)"
ondragover="allowDrop(event)"></div>
<img id="drag1" src="images/excercises/image2.jpg" draggable="true"
ondragstart="drag(event)" width="336" height="69">
答案 0 :(得分:1)
首先,修复第二张图片的ID。 (它与第一个img相同)
然后,为每个DIV添加一个属性,其内容是您要放入的图像ID
data-drop="drag1"
在drop函数中设置一个小条件
function drop(ev)
{
ev.preventDefault();
var data=ev.dataTransfer.getData("Text");
//allow drop only if an ID attribute of the image is the same as specified in a DIV attribute
if(ev.target.getAttribute('data-drop') == data)
ev.target.appendChild(document.getElementById(data));
}
修改强>