drag拖拽
话不多说,直接上代码
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Untitled Document</title>
<style>
* {
padding: 0px;
margin: 0px;
box-sizing: border-box;
}
body {
display: flex;
justify-content: center;
align-items: center;
}
.list {
height: 600px;
width: 600px;
font-weight: 700;
font-size: 36px;
cursor: move;
user-select: none;
display: flex;
flex-direction: column;
justify-content: space-between;
}
.list>.list-item {
height: 100px;
width: 100%px;
background: #6da2eb;
display: flex;
justify-content: center;
align-items: center;
color: white;
border-radius: 15px;
}
.list-item:first-child {
background-color: #1ABC9C;
}
.list-item:nth-child(2) {
background-color: #2980B9;
}
.list-item:nth-child(3) {
background-color: #9B59B6;
}
.list-item:nth-child(4) {
background-color: #F39C12;
}
.list-item:last-child {
background-color: #C0392B;
}
.list>.list-item.moving {
background: transparent;
color: transparent;
border: 1px dashed #ccc;
}
</style>
</head>
<script src="jquery.js"></script>
<body>
<div class="list">
<div draggable="true" class="list-item">A</div>
<div draggable="true" class="list-item">B</div>
<div draggable="true" class="list-item">C</div>
<div draggable="true" class="list-item">D</div>
<div draggable="true" class="list-item">E</div>
</div>
</body>
<script type="text/javascript">
const list = document.querySelector(".list");
//当前操作节点
let currNode;
list.ondragstart = (e) => {
setTimeout(() => {
e.target.classList.add("moving")
}, 0)
currNode = e.target;
//设置鼠标样式
e.dataTransfer.effectAllowed = "move";
}
list.ondragover = (e) => {
e.preventDefault();
}
list.ondragenter = (e) => {
//允许占用
e.preventDefault();
if (e.target === list || e.target === currNode) {
return;
}
const children = Array.from(list.children);
const currNodeIndex = children.indexOf(currNode);
const targetNodeIndex = children.indexOf(e.target);
if (currNodeIndex < targetNodeIndex) {
console.log("向下拖动")
list.insertBefore(currNode, e.target.nextElementSibling);
} else {
list.insertBefore(currNode, e.target);
}
console.log(e.target);
}
list.ondragend = (e) => {
e.target.classList.remove("moving");
}
</script>
</html>