<ul id="sortable" class="sortable">
<li><div class="handle">⋮⋮</div> 項目 1</li>
<li><div class="handle">⋮⋮</div> 項目 2</li>
<li><div class="handle">⋮⋮</div> 項目 3</li>
<li><div class="handle">⋮⋮</div> 項目 4</li>
</ul>
<style>
.sortable { list-style: none; padding: 0; max-width: 400px; }
.sortable li { display: flex; align-items: center; padding: 12px 16px; background: #fff; border: 1px solid #e0e0e0; margin-bottom: 8px; cursor: grab; transition: box-shadow .2s, transform .2s; }
.sortable li.dragging { opacity: .5; box-shadow: 0 8px 24px rgba(0,0,0,.15); cursor: grabbing; }
.sortable li.placeholder { background: #e3f2fd; border: 2px dashed #1976d2; min-height: 48px; }
.handle { margin-right: 12px; color: #999; user-select: none; }
</style>
<script>
class SortableList {
constructor(listEl, options = {}) {
this.list = listEl;
this.handleSel = options.handle || '.handle';
this.animationMs = options.animation || 200;
this.items = [...this.list.children];
this.dragged = null;
this.placeholder = null;
this._bind();
}
_bind() {
this.list.addEventListener('pointerdown', e => {
const handle = e.target.closest(this.handleSel);
if (!handle) return;
const item = handle.closest('li');
if (!item) return;
this._startDrag(item, e);
});
}
_startDrag(item, e) {
this.dragged = item;
item.classList.add('dragging');
item.style.position = 'relative';
item.style.zIndex = 1000;
// 建立佔位元素
this.placeholder = document.createElement('li');
this.placeholder.className = 'placeholder';
this.placeholder.style.height = item.offsetHeight + 'px';
this.list.insertBefore(this.placeholder, item.nextSibling);
const startY = e.clientY;
const startTop = item.offsetTop;
const onMove = e => {
const dy = e.clientY - startY;
item.style.transform = `translateY(${dy}px)`;
this._checkReorder(item, startTop + dy);
};
const onUp = () => {
document.removeEventListener('pointermove', onMove);
document.removeEventListener('pointerup', onUp);
item.classList.remove('dragging');
item.style.position = '';
item.style.zIndex = '';
item.style.transform = '';
this.list.replaceChild(item, this.placeholder);
this.placeholder = null;
this.dragged = null;
this.items = [...this.list.children];
};
document.addEventListener('pointermove', onMove);
document.addEventListener('pointerup', onUp);
}
_checkReorder(dragged, currentTop) {
const items = this.items.filter(li => li !== dragged);
for (const item of items) {
const itemTop = item.offsetTop;
const itemMid = itemTop + item.offsetHeight / 2;
if (currentTop < itemMid && dragged.compareDocumentPosition(item) & Node.DOCUMENT_POSITION_FOLLOWING) {
this.list.insertBefore(dragged, item);
this.items = [...this.list.children];
break;
}
if (currentTop > itemMid && dragged.compareDocumentPosition(item) & Node.DOCUMENT_POSITION_PRECEDING) {
this.list.insertBefore(dragged, item.nextSibling);
this.items = [...this.list.children];
break;
}
}
}
}
// 初始化
new SortableList(document.getElementById('sortable'));
</script>
| 技術 | 說明 |
|---|---|
| `pointerdown/move/up` | 統一鼠標/觸控/筆事件,無需分開寫 `mousedown`/`touchstart` |
| `closest()` | 向上尋找最近符合選擇器的祖先,替代舊式 `while(parent)` 迴圈 |
| `compareDocumentPosition` | 標準 DOM API 判斷節點前後關係,替代手動索引比較 |
| 佔位元素 | 保持列表高度不塌陷,視覺上平滑 |
| `transform: translateY` | 僅觸發合成器層,不觸發重排,動畫絲滑 |
可拖曳排序列表的核心在於:**事件統一(Pointer Events)、視覺佔位、DOM 就地移動、Transform 動畫**。現代瀏覽器原生 API 已足夠強大,無需 jQuery UI Sortable 等重型庫。若專案需求複雜(跨列表、巢狀、虛擬列表),直接上 SortableJS 或 @dnd-kit,別重複造輪子。