萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

原生 JavaScript 實現任意元素拖拽移動(含邊界限制與觸控支援)

拖拽互動是豐富 Web 應用的基石。本文從原理出發,逐步構建一個可復用的 Draggable 類別,支援滑鼠與觸控、可選邊界限制、自動處理滾動容器,並解釋事件捕獲與 setPointerCapture 的現代用法。

核心原理三步驟

  1. mousedown / touchstart:記錄起始指標位置與元素初始位置,綁定全域移動/結束事件。
  2. mousemove / touchmove:計算位移增量,更新元素 transform: translate() 或 left/top。
  3. mouseup / touchend:清理事件監聽器,釋放指標捕獲。

現代實現:使用 Pointer Events 統一滑鼠/觸控/筆輸入

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 vs left/top:transform 不觸發重排,動畫更流暢;需確保元素 position: absolute/fixed 或為 flex/grid 子項。
  • setPointerCapture:解決滑鼠移出元素邊界時事件丟失問題,取代舊式 setCapture/captureEvents。
  • 觸控支援:pointerdown 自動涵蓋 touch,無需額外監聽 touchstart。
  • 邊界限制:透過 getBoundingClientRect 即時計算,支援父容器滾動場景。

延伸:拖拽排序、調整大小

同樣原理可擴展為:Sortable 列表拖拽排序、Resizable 邊緣調整尺寸,核心皆為指標位置映射到 DOM 幾何屬性。

copyright © 萬盛學電腦網 all rights reserved