<!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>
* {
list-style: none;
text-decoration: none;
color: black;
}
#root {
width: 380px;
height: 180px;
margin: 0 auto;
background-color: yellowgreen;
}
#box {
width: 150px;
height: 150px;
background-color: green;
}
.moving_box {
/* position: absolute; */
width: 50px;
height: 50px;
background-color: purple;
}
.root_item {
width: 380px;
height: 30px;
margin-top: 5px;
background-color: pink;
}
.moving {
background-color: transparent;
color: transparent;
border: 1px dotted #ccc;
}
</style>
</head>
<body>
<div id="root">
<div draggable="true" class="root_item">1</div>
<div draggable="true" class="root_item">2</div>
<div draggable="true" class="root_item">3</div>
<div draggable="true" class="root_item">4</div>
<div draggable="true" class="root_item">5</div>
</div>
<div id="box">
<div class="moving_box" draggable="true"></div>
</div>
<script type="text/javascript">
let root = document.querySelector('#root');
let sourceNode;
root.addEventListener('dragstart', function (event) {
setTimeout(() => {
event.target.classList.add('moving');
}, 0);
sourceNode = event.target;
})
root.addEventListener('dragover', function (event) {
event.preventDefault();
})
root.addEventListener('dragenter', function (event) {
event.preventDefault();
if (event.target == root || event.target == sourceNode) {
return
}
let children = [...root.children];
let sourceIndex = children.indexOf(sourceNode);
let currentIndex = children.indexOf(event.target);
if (sourceIndex < currentIndex) {
root.insertBefore(sourceNode, event.target.nextElementSibling);
} else {
root.insertBefore(sourceNode, event.target);
}
})
root.addEventListener('dragend', function (event) {
event.target.classList.remove('moving');
})
</script>
</body>
</html>
前端用拖拽API写一个简单拖拽排序功能
最新推荐文章于 2024-06-13 02:48:16 发布