
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>拖动替换</title>
</head>
<style>
body {
display: flex;
padding: 100px;
}
div {
width: 100px;
height: 100px;
text-align: center;
line-height: 100px;
color: white;
margin-right: 10px;
}
</style>
<body>
<div style="background: purple;" draggable="true">div1</div>
<div style="background: orange;" draggable="true">div2</div>
<div style="background: aqua;" draggable="true">div3</div>
</body>
</html>
<script>
let div = document.getElementsByTagName("div");
let container = null;
for (let i = 0; i < div.length; i++) {
div[i].ondragstart = function () {
container = this;
}
div[i].ondragover = function () {
event.preventDefault();
}
div[i].ondrop = function () {
if (container != null && container != this) {
let temp = document.createElement("div");
document.body.replaceChild(temp, this);
document.body.replaceChild(this, container);
document.body.replaceChild(container, temp);
}
}
}
</script>