帮我用js写一个拖动排序
时间: 2023-07-20 10:08:38 浏览: 87
好的,以下是一个简单的用 JavaScript 实现拖动排序的示例代码:
HTML 代码:
```html
<ul id="sortable">
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
<li>Item 5</li>
</ul>
```
JavaScript 代码:
```javascript
const sortable = document.getElementById("sortable");
let draggingEl = null;
let draggingOffsetX = 0;
let draggingOffsetY = 0;
sortable.addEventListener("mousedown", (event) => {
if (event.target.nodeName === "LI") {
draggingEl = event.target;
draggingOffsetX = event.clientX - draggingEl.offsetLeft;
draggingOffsetY = event.clientY - draggingEl.offsetTop;
draggingEl.classList.add("dragging");
}
});
document.addEventListener("mousemove", (event) => {
if (draggingEl !== null) {
event.preventDefault();
draggingEl.style.left = event.clientX - draggingOffsetX + "px";
draggingEl.style.top = event.clientY - draggingOffsetY + "px";
}
});
document.addEventListener("mouseup", (event) => {
if (draggingEl !== null) {
draggingEl.classList.remove("dragging");
const targetEl = document.elementFromPoint(event.clientX, event.clientY);
if (targetEl && targetEl.nodeName === "LI") {
if (targetEl !== draggingEl) {
if (targetEl.compareDocumentPosition(draggingEl) & Node.DOCUMENT_POSITION_FOLLOWING) {
targetEl.parentNode.insertBefore(draggingEl, targetEl.nextSibling);
} else {
targetEl.parentNode.insertBefore(draggingEl, targetEl);
}
}
}
draggingEl = null;
}
});
```
CSS 代码:
```css
#sortable {
list-style-type: none;
margin: 0;
padding: 0;
}
#sortable li {
cursor: pointer;
position: absolute;
background-color: #f1f1f1;
border: 1px solid #ddd;
padding: 10px;
width: 200px;
height: 40px;
}
#sortable li.dragging {
opacity: 0.5;
}
```
这里的实现方式是将要拖动的元素设置为绝对定位,然后在 `mousedown` 事件触发时记录偏移量,然后在 `mousemove` 事件触发时根据鼠标位置调整元素位置,最后在 `mouseup` 事件触发时将元素插入到正确的位置。
阅读全文