【发布时间】:2014-05-01 16:14:52
【问题描述】:
我有一些非常简单的代码,允许我将图像拖放到不同的框中。当图像被删除时,它的父节点将其删除,并且它被放置到的区域会附加它。这很好用。但是,如果我将一个图像拖放到另一个图像上,那么由于某种原因会触发相同的 ondrop 事件,因此该图像最终会被删除,但不会被重新插入。
我已经尝试了几件事来解决这个问题:添加第二个什么都不做的 drop 函数并将图像的 ondrop 属性设置为此,为返回 false 的图像创建一个“disallowdrop”函数,这两个都不起作用。当某些东西被拖放到图像上时,应该没有理由调用 drop 函数。无论如何,我认为元素默认不接受拖动元素。
这是我的代码:
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
.area {
height:150px;
width:400px;
border:2px solid;
}
</style>
</head>
<body onload="load()">
<script type="text/javascript">
function load() {
var bottom = document.getElementById("bottom");
bottom.appendChild(newDraggableImage("square.jpg", 1));
bottom.appendChild(newDraggableImage("triangle.jpg", 2));
bottom.appendChild(newDraggableImage("circle.jpg", 3));
}
function newDraggableImage(source, id) {
var image = document.createElement('img');
image.src = source;
image.id = id;
image.draggable = true;
image.ondragstart = drag;
return image;
}
function drop(event) {
event.preventDefault();
var image = document.getElementById(event.dataTransfer.getData('Text'));
image.parentElement.removeChild(image);
event.target.appendChild(image);
}
function allowDrop(event) {
event.preventDefault();
}
function drag(event) {
event.dataTransfer.setData('Text', event.target.id);
}
</script>
<div id="top" class="area" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
<div id="bottom" class="area" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
</body>
</html>
【问题讨论】: