Javascript HTML5和JS将多个图像拖放到特定位置

Javascript HTML5和JS将多个图像拖放到特定位置,javascript,html,drag-and-drop,Javascript,Html,Drag And Drop,我尝试有2个可拖动的图像和2个目标位置,但我希望image1只能在位置1中拖放,image2只能在位置2中拖放,此代码允许在任意位置拖放任何一个图像 (为了便于阅读,我省略了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 #aaaa

我尝试有2个可拖动的图像和2个目标位置,但我希望image1只能在位置1中拖放,image2只能在位置2中拖放,此代码允许在任意位置拖放任何一个图像

(为了便于阅读,我省略了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">

功能allowDrop(ev)
{
ev.preventDefault();
}
功能阻力(ev)
{
ev.dataTransfer.setData(“文本”,ev.target.id);
}
功能下降(ev)
{
ev.preventDefault();
var data=ev.dataTransfer.getData(“文本”);
ev.target.appendChild(document.getElementById(数据));
}

首先,修复第二张图像的ID。(与第一个img相同)

然后,在每个div中添加一个属性,该属性的内容是image的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));

}
编辑


首先,修复第二张图像的ID。(与第一个img相同)

然后,在每个div中添加一个属性,该属性的内容是image的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));

}
编辑


谢谢,但我不确定在哪里添加data drop=“drag1”?我提供了一个指向在线编辑器的链接,很抱歉我没有更早发布它,我无法在JSFIDLE上使用它。谢谢,我不确定在哪里添加data drop=“drag1”?我提供了指向在线编辑器的链接,很抱歉我没有更早发布它,我无法在JSFIDLE上使用它