<!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-item {
display: flex;
align-items: center;
justify-content: center;
background: #f50;
height: 30px;
width: 300px;
color: #fff;
cursor: move;
user-select: none;
border-radius: 5px;
margin-bottom: 10px;
}
.list-item.moving {
background: transparent;
color: transparent;
border: 1px dashed #ccc;
}
</style>
</head>
<!-- 使用filp 动画 -->
<body>
<div class="list">
<div class="list-item" draggable="true">1</div>
<div class="list-item" draggable="true">2</div>
<div class="list-item" draggable="true">3</div>
<div class="list-item" draggable="true">4</div>
<div class="list-item" draggable="true">5</div>
</div>
<script>
const list = document.querySelector('.list')
let sourceNode //当前正在拖动的是哪个元素
// let filp;
list.ondragstart = (e) => {
setTimeout(() => {
//延迟添加样式
e.target.classList.add('moving')
}, 0)
sourceNode = e.target
e.dataTransfer.effectAllowed='move'//修改鼠标
console.log( e.dataTransfer.effectAllover);
// file=new Filp(list.children,0.3)
}
list.ondragover = (e) => {
e.preventDefault();
}
//使用父做事件代理
list.ondragenter = (e) => {
e.preventDefault();
if (e.target === list || e.target === sourceNode) {
return
}
const children = Array.from(list.children);
const sourceIndex = children.indexOf(sourceNode);
const targetIndex = children.indexOf(e.target);
//往上拖
if (sourceIndex < targetIndex) {
//往下拖
list.insertBefore(sourceNode, e.target.nextElementSibling);
} else {
//往上拖
list.insertBefore(sourceNode, e.target);
}
// filp.play()
}
//移除moving
list.ondragend=(e)=>{
e.target.classList.remove('moving');
}
//默认情况下 元素不允许别的元素拖到自身之上的 拖动行为会取消
</script>
</body>
</html>
标签:const,sourceNode,list,拖曳,moving,排序,children,target
From: https://www.cnblogs.com/7c89/p/17962199