<!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>
<style>
.box {
width: 200px;
height: 40px;
margin-bottom: 20px;
background-color: palegoldenrod;
cursor: pointer;
}
.moving {
background-color: transparent;
border: 1px solid #333;
}
</style>
</head>
<body>
<div class="list">
<div class="box" draggable="true">111</div>
<div class="box" draggable="true">222</div>
<div class="box" draggable="true">333</div>
<div class="box" draggable="true">444</div>
<div class="box" draggable="true">555</div>
</div>
<script>
const list_dom = document.querySelector(".list")
let sourceNode
list_dom.ondragstart = e => {
setTimeout(() => {
e.target.classList.add('moving')
}, 0);
e.dataTransfer.effectAllowed = "move" // 取消拖拽时光标自带的绿色加号
sourceNode = e.target
}
list_dom.ondragover = e => {
e.preventDefault() // 拖动元素默认会回到其初始位置,需要阻止默认行为
}
list_dom.ondragenter = e => {
// e.preventDefault()
// 如果拖动到本身,或者最大父元素中,不做处理
if (e.target === list_dom || e.target === sourceNode) {
return
}
const children = [...list_dom.children]
const sourceIndex = children.indexOf(sourceNode)
const targetIndex = children.indexOf(e.target)
if (sourceIndex < targetIndex) {
// 向下拖动
list_dom.insertBefore(sourceNode, e.target.nextElementSibling)
} else {
// 向上拖动
list_dom.insertBefore(sourceNode, e.target)
}
}
list_dom.ondragend = e => {
e.target.classList.remove('moving')
}
</script>
</body>
</html>
标签:target,dom,拖动,list,JS,排序,children,sourceNode
From: https://blog.csdn.net/owo_ovo/article/details/137139256