萬盛學電腦網

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

JavaScript 實作拖曳功能:閉包封裝與滑鼠/觸控雙支援

閉包封裝優勢

  • 私有狀態(dragState)不汙染全域
  • 單一實例管理多個可拖曳元素
  • 介面乾淨:DragManager.register(el), DragManager.enable(), DragManager.disable()

完整現代化實作

const DragManager = (function() {
    // 私有狀態
    const state = {
        draggingEl: null,
        startX: 0,
        startY: 0,
        initialLeft: 0,
        initialTop: 0,
        isPointerDown: false,
        boundary: null // {minX, maxX, minY, maxY} 或 null 表無限制
    };

    // 統一取得座標
    function getClientXY(e) {
        if (e.touches && e.touches.length) return {x: e.touches[0].clientX, y: e.touches[0].clientY};
        return {x: e.clientX, y: e.clientY};
    }

    // 邊界限制
    function clamp(value, min, max) {
        return Math.max(min, Math.min(max, value));
    }

    function onPointerDown(e) {
        const handle = e.target.closest('[data-drag-handle]');
        if (!handle) return; // 僅允許把手區域啟動
        const el = handle.closest('[data-draggable]');
        if (!el) return;

        e.preventDefault(); // 防止文字選取、觸控滾動
        const {x, y} = getClientXY(e);

        state.draggingEl = el;
        state.startX = x;
        state.startY = y;
        state.initialLeft = el.offsetLeft;
        state.initialTop = el.offsetTop;
        state.isPointerDown = true;

        // 計算邊界(相對 offsetParent)
        if (state.boundary) {
            const parent = el.offsetParent;
            state.boundary = {
                minX: 0,
                maxX: parent.clientWidth - el.offsetWidth,
                minY: 0,
                maxY: parent.clientHeight - el.offsetHeight
            };
        }

        // 全域監聽
        document.addEventListener('mousemove', onPointerMove);
        document.addEventListener('mouseup', onPointerUp);
        document.addEventListener('touchmove', onPointerMove, {passive: false});
        document.addEventListener('touchend', onPointerUp);
        document.addEventListener('touchcancel', onPointerUp);

        el.classList.add('dragging');
        handle.style.cursor = 'grabbing';
    }

    function onPointerMove(e) {
        if (!state.isPointerDown || !state.draggingEl) return;
        e.preventDefault();

        const {x, y} = getClientXY(e);
        const dx = x - state.startX;
        const dy = y - state.startY;

        let newLeft = state.initialLeft + dx;
        let newTop = state.initialTop + dy;

        if (state.boundary) {
            newLeft = clamp(newLeft, state.boundary.minX, state.boundary.maxX);
            newTop = clamp(newTop, state.boundary.minY, state.boundary.maxY);
        }

        state.draggingEl.style.left = newLeft + 'px';
        state.draggingEl.style.top = newTop + 'px';
    }

    function onPointerUp() {
        if (!state.isPointerDown) return;
        state.isPointerDown = false;

        document.removeEventListener('mousemove', onPointerMove);
        document.removeEventListener('mouseup', onPointerUp);
        document.removeEventListener('touchmove', onPointerMove);
        document.removeEventListener('touchend', onPointerUp);
        document.removeEventListener('touchcancel', onPointerUp);

        if (state.draggingEl) {
            state.draggingEl.classList.remove('dragging');
            const handle = state.draggingEl.querySelector('[data-drag-handle]');
            if (handle) handle.style.cursor = 'move';
            state.draggingEl = null;
        }
    }

    // 公開 API
    return {
        register(el) {
            if (!el.hasAttribute('data-draggable')) {
                el.setAttribute('data-draggable', '');
            }
            // 確保定位
            if (getComputedStyle(el).position === 'static') {
                el.style.position = 'absolute';
            }
        },
        enable() {
            document.addEventListener('mousedown', onPointerDown);
            document.addEventListener('touchstart', onPointerDown, {passive: false});
        },
        disable() {
            document.removeEventListener('mousedown', onPointerDown);
            document.removeEventListener('touchstart', onPointerDown);
        },
        setBoundary(boundary) {
            state.boundary = boundary;
        }
    };
})();

// 初始化
document.addEventListener('DOMContentLoaded', () => {
    document.querySelectorAll('[data-draggable]').forEach(el => DragManager.register(el));
    DragManager.enable();
});

HTML 使用範例

<div class="window" data-draggable style="left:100px;top:100px;width:300px;height:200px;">
    <div class="title-bar" data-drag-handle>標題列(把手)</div>
    <div class="content">內容區域</div>
</div>

<style>
.window { position:absolute; border:1px solid #ccc; background:#fff; border-radius:8px; box-shadow:0 4px 12px rgba(0,0,0,.15); user-select:none; }
.title-bar { height:36px; background:#007bff; color:#fff; display:flex; align-items:center; padding:0 12px; cursor:move; border-radius:8px 8px 0 0; user-select:none; }
.title-bar.dragging { cursor:grabbing; }
.content { padding:12px; }
[data-draggable].dragging { z-index:9999; box-shadow:0 8px 24px rgba(0,0,0,.2); }
</style>

原始碼重構對照

原始碼問題現代重構改善
全域變數 posX, posY, dragbegin...閉包內 state 物件封裝
直接賦值 onmousedown 覆蓋舊處理器addEventListener 可多綁、可移除
僅支援滑鼠統一 getClientXY 支援觸控
無邊界限制可選 boundary 限制在容器內
無視覺回饋CSS .dragging 狀態、游標變化
硬編碼元素 IDdata-draggable/data-drag-handle 語意屬性,支援多實例
parseInt(style.left) 易碎offsetLeft/Top 直接取得數值

進階擴充

  • 磁吸對齊:在 onPointerUp 計算最近網格點
  • 碰撞偵測:用 getBoundingClientRect() 檢查與其他元素重疊
  • 持久化:localStorage.setItem('dragPos', JSON.stringify({left, top}))
  • 調整大小:結合 ResizeObserver 或右下角把手
  • 桌面級體驗:引入 InteractJS、SortableJS、dnd-kit 處理複雜拖放排序
copyright © 萬盛學電腦網 all rights reserved