gpt4 book ai didi

JavaScript 拖放类/ID 问题

转载 作者:行者123 更新时间:2023-11-30 10:17:52 29 4
gpt4 key购买 nike

我有这个脚本可以将一个 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 时,它停止工作。这对我来说完全没有意义。请帮忙?

最佳答案

http://jsfiddle.net/t98ZD/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;
}

关于JavaScript 拖放类/ID 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22947411/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com