HTML5 拖放
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/e3de027ebf3b8d57183375b80c57111f.gif#pic_center)
<!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>Document</title>
</head>
<style>
div {
display: flex;
justify-content: center;
align-items: center;
}
div>p>span {
width: 400px;
height: 40px;
display: block;
margin: 10px;
}
div>p:nth-child(1)>span {
background-color: red;
}
div>p:nth-child(2)>span {
background-color: green;
}
</style>
<body>
<div>
<p>
<span id="p1-1" draggable="true">p1-1</span>
<span id="p1-2" draggable="true">p1-2</span>
<span id="p1-3" draggable="true">p1-3</span>
<span id="p1-4" draggable="true">p1-4</span>
<span id="p1-5" draggable="true">p1-5</span>
<span id="p1-6" draggable="true">p1-6</span>
<span id="p1-7" draggable="true">p1-7</span>
<span id="p1-8" draggable="true">p1-8</span>
<span id="p1-9" draggable="true">p1-9</span>
<span id="p1-10" draggable="true">p1-10</span>
</p>
<p>
<span id="p2-1" draggable="true">p2-1</span>
<span id="p2-2" draggable="true">p2-2</span>
<span id="p2-3" draggable="true">p2-3</span>
<span id="p2-4" draggable="true">p2-4</span>
<span id="p2-5" draggable="true">p2-5</span>
<span id="p2-6" draggable="true">p2-6</span>
<span id="p2-7" draggable="true">p2-7</span>
<span id="p2-8" draggable="true">p2-8</span>
<span id="p2-9" draggable="true">p2-9</span>
<span id="p2-10" draggable="true">p2-10</span>
</p>
</div>
</body>
</html>
<script>
var spanList = document.getElementsByTagName("span");
for (const item of spanList) {
item.ondragstart = this.dragStart;
item.ondrag = this.onDrag;
item.ondragend = this.endDrag;
item.ondragenter = this.enterDrag;
item.ondragover = this.dragOverfun;
item.ondrop = this.dropDrag;
}
function dragStart(env) {
env.dataTransfer.setData("dom", this.getAttribute("id"));
console.log('开始')
}
function onDrag() {
console.log('拖拽中')
}
function dragOverfun(env) {
env.preventDefault();
}
function endDrag() {
console.log('结束')
}
function enterDrag() {
console.log('进入目标区域')
}
function dropDrag(env) {
let parent = env.toElement.parentNode;
var data = env.dataTransfer.getData("dom");
let dragDom = document.getElementById(data);
parent.insertBefore(dragDom, env.toElement);
}
</script>