HTML5拖放 - 尝试拖动元素而不是从源div中删除它

时间:2017-07-12 17:06:40

标签: javascript html5 drag-and-drop

我将元素拖放到目标div,也不将其从源div中删除

使用下面的代码拖放工作正常,但我试图保留源div中的元素而不删除它

HTML:

<html>
<head>
</head>
<body>

<p>Drag the elements image into the rectangle:</p>

<div id="div1" ondrop="drop(event)" ondragover="allowDrop(event)">
  <div id="drag1" draggable="true" ondragstart="drag(event)" width="336" height="69">Input</div>
  <div id="drag2" draggable="true" ondragstart="drag(event)" width="336" height="69">Radio</div>
  <div id="drag3" draggable="true" ondragstart="drag(event)" width="336" height="69">Checkbox</div>
  <div id="drag4" draggable="true" ondragstart="drag(event)" width="336" height="69">Dropdown</div>
  </div>  
  <br>
<div id="div2" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
<br>

</body>
</html>

JS:

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));
}

CSS:

#div1, #div2 {
    width: 350px;
    height: 100px;
    padding: 10px;
    border: 1px solid #aaaaaa;
}

#drag1,#drag2,#drag3,#drag4{
  border:1px solid black;
  margin:5px;
}

0 个答案:

没有答案