拖拽排序功能还是挺常见的, 涉及到的api 还是挺多的,这里笔记记录一下以免忘记找不到了!
老规矩先上效果图
html部分
<div class="list-box"><div draggable="true" class="item">1</div><div draggable="true" class="item">2</div><div draggable="true" class="item">3</div><div draggable="true" class="item">4</div><div draggable="true" class="item">5</div><div draggable="true" class="item">6</div></div>
js 部分
<script>const list = document.querySelector('.list-box');let sourceNode;list.ondragstart = (e) => {setTimeout(() => {e.target.classList.add('moving');}, 0)sourceNode = e.target};list.ondragover = (e) => {e.preventDefault();};list.ondragenter = (e) => {e.preventDefault();if (e.target == list || e.target == sourceNode) return;const chidList = [...list.children]const sourceIndex = chidList.indexOf(sourceNode);const targetIndex = chidList.indexOf(e.target);if (sourceIndex < targetIndex) {list.insertBefore(sourceNode, e.target.nextElementSibling)} else {list.insertBefore(sourceNode, e.target)}};list.ondragend = () => {sourceNode.classList.remove('moving')} </script>
css 部分 这个图拽动画 要是相弄得好看还是有难度的 ,我就随便写了点样式
<style>.list-box {list-style: none;width: 500px;margin: 0 auto;}.item {background: aquamarine;height: 40px;line-height: 40px;border-radius: 4px;margin-bottom: 10px;user-select: none;transition: background-color 0.3s ease;}.item.moving {background: transparent;color: transparent;border: 1px dashed #ccc;transition: none;}</style>