我有这个脚本将div拖入另一个div:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<style>
.content {
width: 300px;
height: 300px;
border: 1px solid black;
}
#dragme {
height:50px;
width:50px;
background-color: blue;
}
</style>
</head>
<body>
<div class="content" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
<div id="dragme" draggable="true" ondragstart="drag(event)">Drag me!</div>
<script>
function allowDrop(ev) {
ev.preventDefault();
}
function drag(ev) {
ev.dataTransfer.setData("dragged-id", ev.target.id);
}
function drop(ev) {
ev.preventDefault();
var data = ev.dataTransfer.getData("dragged-id");
ev.target.appendChild(document.getElementById(data));
}
</script>
</body>
</html>
一切正常,但是当我将“dragme”div从id更改为class时,它会停止工作。这对我来说完全没有意义。请帮帮忙?
答案 0 :(得分:3)
<body>
<div class="content" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
<div class="dragme" draggable="true" ondragstart="drag(event)">Drag me!</div>
<script>
function allowDrop(ev) {
ev.preventDefault();
}
function drag(ev) {
ev.dataTransfer.setData("dragged-id", ev.target.className);
}
function drop(ev) {
ev.preventDefault();
var data = ev.dataTransfer.getData("dragged-id");
ev.target.appendChild(document.getElementsByClassName(data)[0]);
}
</script>
</body>
CSS:
.dragme {
height:50px;
width:50px;
background-color: blue;
}
答案 1 :(得分:1)
这就是它的工作原理:document.getElementById(data)