拖拽互動是豐富 Web 應用的基石。本文從原理出發,逐步構建一個可復用的 Draggable 類別,支援滑鼠與觸控、可選邊界限制、自動處理滾動容器,並解釋事件捕獲與 setPointerCapture 的現代用法。
transform: translate() 或 left/top。class Draggable {
constructor(el, { boundary = null, handle = null } = {}) {
this.el = el;
this.boundary = boundary; // 可選:限制邊界的父元素
this.handle = handle || el; // 拖拽手柄,預設為元素本身
this._start = { x: 0, y: 0 };
this._pos = { x: 0, y: 0 };
this._bind();
}
_bind() {
this.handle.addEventListener('pointerdown', this._onDown.bind(this));
}
_onDown(e) {
if (e.button !== 0 && e.pointerType !== 'touch') return; // 僅左鍵/觸控
e.preventDefault();
this.handle.setPointerCapture(e.pointerId); // 關鍵:捕獲後續事件
const rect = this.el.getBoundingClientRect();
this._start = { x: e.clientX - rect.left, y: e.clientY - rect.top };
this._pos = { x: rect.left, y: rect.top };
document.addEventListener('pointermove', this._onMove.bind(this));
document.addEventListener('pointerup', this._onUp.bind(this));
}
_onMove(e) {
let x = e.clientX - this._start.x;
let y = e.clientY - this._start.y;
if (this.boundary) {
const bRect = this.boundary.getBoundingClientRect();
const eRect = this.el.getBoundingClientRect();
x = Math.max(bRect.left, Math.min(x, bRect.right - eRect.width));
y = Math.max(bRect.top, Math.min(y, bRect.bottom - eRect.height));
}
this.el.style.transform = `translate(${x}px, ${y}px)`;
}
_onUp(e) {
this.handle.releasePointerCapture(e.pointerId);
document.removeEventListener('pointermove', this._onMove);
document.removeEventListener('pointerup', this._onUp);
}
}
// 使用
new Draggable(document.getElementById('box'), {
boundary: document.getElementById('container'),
handle: document.getElementById('box-handle')
});
transform 不觸發重排,動畫更流暢;需確保元素 position: absolute/fixed 或為 flex/grid 子項。setCapture/captureEvents。pointerdown 自動涵蓋 touch,無需額外監聽 touchstart。getBoundingClientRect 即時計算,支援父容器滾動場景。同樣原理可擴展為:Sortable 列表拖拽排序、Resizable 邊緣調整尺寸,核心皆為指標位置映射到 DOM 幾何屬性。