<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>拖拽排序</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
ul {
margin: 20px auto;
width: 200px;
list-style-type: none;
}
li {
margin: 5px;
text-align: center;
width: 200px;
height: 30px;
background: skyblue;
}
.list .moving {
background: transparent;
color: transparent;
border: 1px dashed #ccc;
}
</style>
</head>
<body>
可拖动排序,改变数组,
<div id="Application">
<ul class="list" v-model="checkList">
<li draggable="true" value="1">1</li>
<li draggable="true" value="2">2</li>
<li draggable="true" value="3">3</li>
<li draggable="true" value="4">4</li>
<li draggable="true" value="5">5</li>
</ul>
<ul>
您的数据排序是:<h2 id="view"></h2>
</ul>
</div>
</body>
</html>
<script type="text/javascript">
const forli = () => {
var arr = document.getElementsByTagName('li');
var temp = [];
for (var i = 0; i < arr.length; i++) {
temp.push(arr[i].innerHTML)
div = document.getElementById("view");
div.innerHTML = JSON.stringify(temp);
}
}
forli();
let list = document.querySelector('.list')
let currentLi
list.addEventListener('dragstart', (e) => {
e.dataTransfer.effectAllowed = 'move'
currentLi = e.target
setTimeout(() => {
currentLi.classList.add('moving')
})
})
list.addEventListener('dragenter', (e) => {
e.preventDefault()
if (e.target === currentLi || e.target === list) {
return
}
let liArray = Array.from(list.childNodes)
let currentIndex = liArray.indexOf(currentLi)
let targetindex = liArray.indexOf(e.target)
if (currentIndex < targetindex) {
list.insertBefore(currentLi, e.target.nextElementSibling)
} else {
list.insertBefore(currentLi, e.target)
}
})
list.addEventListener('dragover', (e) => {
e.preventDefault();
forli();
})
list.addEventListener('dragend', (e) => {
currentLi.classList.remove('moving')
})
</script>