萬盛學電腦網

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

JavaScript 完美 Div 拖曳元件:可配置邊界限制、軸向鎖定、回調事件的完整實作

功能特性

  • 指定把手觸發拖曳
  • 容器邊界限制
  • 水平/垂直/完全鎖定
  • 開始/移動/結束回調
  • 相容滑鼠與觸控(可擴充)

核心 Drag 類別(ES6 重寫版)


class Drag {
  /**
   * @param {HTMLElement|string} el 目標元素或選擇器
   * @param {Object} options
   * @param {HTMLElement|string} options.handle - 拖曳把手(預設目標自身)
   * @param {HTMLElement|string} options.container - 限制容器(預設 viewport)
   * @param {boolean} options.limit - 限制在容器內(預設 true)
   * @param {boolean} options.lockX - 鎖定水平
   * @param {boolean} options.lockY - 鎖定垂直
   * @param {boolean} options.lock - 完全鎖定
   * @param {Function} options.onStart - 開始回調
   * @param {Function} options.onMove - 移動回調
   * @param {Function} options.onStop - 結束回調
   */
  constructor(el, options = {}) {
    this.el = typeof el === "string" ? document.querySelector(el) : el;
    this.handle = typeof options.handle === "string" 
      ? document.querySelector(options.handle) 
      : options.handle || this.el;
    this.container = typeof options.container === "string"
      ? document.querySelector(options.container)
      : options.container || document.documentElement;

    this.limit = options.limit !== false;
    this.lockX = !!options.lockX;
    this.lockY = !!options.lockY;
    this.lock = !!options.lock;

    this.onStart = options.onStart || (() => {});
    this.onMove = options.onMove || (() => {});
    this.onStop = options.onStop || (() => {});

    this._bindEvents();
    this._initPosition();
  }

  _initPosition() {
    // 確保 absolute 定位且移除 margin 干擾
    this.el.style.position = "absolute";
    this.el.style.margin = "0";
    this.handle.style.cursor = "move";
  }

  _bindEvents() {
    this.handle.addEventListener("mousedown", this._onMouseDown.bind(this));
    // 觸控支援可擴充 touchstart
  }

  _onMouseDown(e) {
    if (e.button !== 0) return; // 僅左鍵
    e.preventDefault();

    const rect = this.el.getBoundingClientRect();
    const cRect = this.container.getBoundingClientRect();

    this.startX = e.clientX - rect.left;
    this.startY = e.clientY - rect.top;

    // 容器邊界
    this.maxLeft = cRect.width - rect.width;
    this.maxTop = cRect.height - rect.height;

    document.addEventListener("mousemove", this._onMouseMove.bind(this));
    document.addEventListener("mouseup", this._onMouseUp.bind(this));

    this.handle.setCapture?.(); // IE/Edge 獨有
    this.onStart();
  }

  _onMouseMove(e) {
    if (this.lock) return;

    let left = e.clientX - this.startX;
    let top = e.clientY - this.startY;

    if (this.limit) {
      left = Math.max(0, Math.min(left, this.maxLeft));
      top = Math.max(0, Math.min(top, this.maxTop));
    }

    if (!this.lockX) this.el.style.left = left + "px";
    if (!this.lockY) this.el.style.top = top + "px";

    this.onMove({ left, top });
  }

  _onMouseUp() {
    document.removeEventListener("mousemove", this._onMouseMove.bind(this));
    document.removeEventListener("mouseup", this._onMouseUp.bind(this));
    this.handle.releaseCapture?.();
    this.onStop();
  }

  // 公開方法:動態切換鎖定
  setLockX(v) { this.lockX = v; }
  setLockY(v) { this.lockY = v; }
  setLock(v) { this.lock = v; }
  setLimit(v) { this.limit = v; }
}

使用範例


<style>
#box { width:100px; height:100px; background:#fef4eb; border:1px solid #f60; position:absolute; }
#box .title { height:25px; background:#f60; }
#tool { margin-bottom:10px; }
</style>

<div id="tool">
  <button data-action="limit">鎖定範圍</button>
  <button data-action="lockX">水平鎖定</button>
  <button data-action="lockY">垂直鎖定</button>
  <button data-action="lock">鎖定位置</button>
</div>
<p>狀態:未開始</p>
<div id="box"><div class="title"></div></div>

<script>
const box = new Drag("#box", {
  handle: "#box .title",
  limit: true,
  onStart: () => status.textContent = "開始拖曳",
  onMove: ({left, top}) => status.textContent = `left:${left}, top:${top}`,
  onStop: () => status.textContent = "結束拖曳"
});

document.querySelectorAll("#tool button").forEach(btn => {
  btn.addEventListener("click", () => {
    const act = btn.dataset.action;
    box[`set${act.charAt(0).toUpperCase() + act.slice(1)}`](!box[act]);
    btn.textContent = box[act] ? `取消${btn.textContent}` : btn.textContent.replace("取消", "");
  });
});
</script>

進階擴充方向

  • 觸控支援:加入 `touchstart/move/end` 事件,處理 `e.touches[0]`。
  • 彈性邊界:超出邊界時彈性拉回(彈簧動畫)。
  • 吸附對齊:移動時自動對齊網格或其他元素。
  • 請求動畫幀:`requestAnimationFrame` 節流渲染,提升流暢度。

總結

封裝為 ES6 Class 的拖曳元件,支援把手指定、容器限制、軸向鎖定、生命週期回調,代碼結構清晰、易擴充。核心邏輯:**滑鼠按下記錄初始偏移 → 移動時計算新位置並套用邊界/鎖定 → 釋放清理事件**。避免全域汙染,方便多實例共存。

copyright © 萬盛學電腦網 all rights reserved