基于原生实现拖拽排序

效果图

tz.png

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
<!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>
.list-item {
width: 300px;
height: 30px;
margin: 20px;
text-align: center;
line-height: 30px;
border-radius: 5px;
background: rgba(32, 138, 191, 0.776);
}
.list-item.moving {
background: transparent;
color: transparent;
border: 1px dashed #ccc;
}
</style>
<body>
<div class="list">
<div draggable="true" class="list-item">1</div>
<div draggable="true" class="list-item">2</div>
<div draggable="true" class="list-item">3</div>
<div draggable="true" class="list-item">4</div>
<div draggable="true" class="list-item">5</div>
</div>
<script>
const list = document.querySelector('.list');
let node
list.ondragstart = function (e) {
setTimeout(() => {
e.target.classList.add('moving');
})
node = e.target;
e.dataTransfer.effectAllowed = 'move';
}
list.ondragover = function (e) {
e.preventDefault();
}
list.ondragenter = function (e) {
e.preventDefault();
if (e.target == list || e.target == node) {
return
}
const children = Array.from(list.children)
const nodeIndex = children.indexOf(node)
const targetIndex = children.indexOf(e.target)
if (nodeIndex < targetIndex) {
// 从上往下拖动
list.insertBefore(node, e.target.nextElementSibling)
} else {
// 从下往上拖动
list.insertBefore(node, e.target)
}
}
list.ondragend = (e) => {
e.target.classList.remove('moving');
}
</script>
</body>
</html>


基于原生实现拖拽排序
http://example.com/2022/11/24/基于原生实现拖拽排序/
作者
dinghw
发布于
2022年11月24日
许可协议