萬盛學電腦網

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

原生 JavaScript 實作可拖曳、可關閉彈出層 (Modal) 完整教學

功能需求

  • 點擊按鈕開啟置中彈出層。
  • 標題列可拖曳移動視窗位置。
  • 右上角關閉按鈕 / 點擊遮罩 / Esc 鍵關閉。
  • 拖曳不超出視窗可視區域。
  • 無依賴、ES6 模組化寫法。

完整實作 (單檔案 Demo)

<!DOCTYPE html>
<html lang="zh-Hant">
<head>
    <meta charset="UTF-8">
    <title>可拖曳可關閉彈出層 Demo</title>
    <style>
        * { box-sizing: border-box; margin: 0; padding: 0; }
        body { font-family: "Microsoft JhengHei", sans-serif; min-height: 100vh; display: flex; align-items: center; justify-content: center; background: #f5f5f5; }
        .btn-open { padding: 12px 24px; font-size: 16px; background: #007bff; color: #fff; border: none; border-radius: 6px; cursor: pointer; }
        .btn-open:hover { background: #0056b3; }

        /* 遮罩層 */
        .modal-overlay {
            position: fixed; inset: 0; background: rgba(0,0,0,0.4);
            display: none; align-items: center; justify-content: center;
            z-index: 1000; opacity: 0; transition: opacity 0.2s;
        }
        .modal-overlay.open { display: flex; opacity: 1; }

        /* 彈出視窗 */
        .modal {
            width: 90%; max-width: 500px; background: #fff; border-radius: 8px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.2);
            transform: scale(0.9); transition: transform 0.2s, opacity 0.2s;
            opacity: 0; display: flex; flex-direction: column;
        }
        .modal-overlay.open .modal { transform: scale(1); opacity: 1; }

        .modal-header {
            display: flex; justify-content: space-between; align-items: center;
            padding: 16px 20px; border-bottom: 1px solid #eee;
            cursor: move; user-select: none; background: #fafafa; border-radius: 8px 8px 0 0;
        }
        .modal-title { font-size: 18px; font-weight: 600; color: #333; }
        .modal-close {
            width: 32px; height: 32px; border: none; background: transparent;
            font-size: 20px; color: #999; cursor: pointer; border-radius: 4px;
            display: flex; align-items: center; justify-content: center;
        }
        .modal-close:hover { background: #eee; color: #333; }
        .modal-body { padding: 20px; color: #555; line-height: 1.6; }
        .modal-footer { padding: 16px 20px; border-top: 1px solid #eee; display: flex; justify-content: flex-end; gap: 8px; border-radius: 0 0 8px 8px; }
        .btn { padding: 8px 16px; border: none; border-radius: 4px; cursor: pointer; font-size: 14px; }
        .btn-primary { background: #007bff; color: #fff; }
        .btn-secondary { background: #e0e0e0; color: #333; }
    </style>
</head>
<body>

    <button class="btn-open" id="openBtn">開啟彈出層</button>

    <div class="modal-overlay" id="overlay" role="dialog" aria-modal="true" aria-labelledby="modalTitle">
        <div class="modal" id="modal">
            <div class="modal-header" id="dragHandle">
                <span class="modal-title" id="modalTitle">彈出層標題</span>
                <button class="modal-close" id="closeBtn" aria-label="關閉">×</button>
            </div>
            <div class="modal-body">
                <p>這是一個可拖曳、可關閉的彈出層範例。</p>
                <p>請嘗試拖曳標題列移動位置。</p>
            </div>
            <div class="modal-footer">
                <button class="btn btn-secondary" id="cancelBtn">取消</button>
                <button class="btn btn-primary" id="confirmBtn">確定</button>
            </div>
        </div>
    </div>

    <script>
        class DraggableModal {
            constructor(options = {}) {
                this.overlay = document.getElementById(options.overlayId || 'overlay');
                this.modal = document.getElementById(options.modalId || 'modal');
                this.dragHandle = document.getElementById(options.dragHandleId || 'dragHandle');
                this.closeBtn = document.getElementById(options.closeBtnId || 'closeBtn');
                this.openBtn = document.getElementById(options.openBtnId || 'openBtn');
                this.onConfirm = options.onConfirm || (() => this.close());
                this.onCancel = options.onCancel || (() => this.close());

                this._dragging = false;
                this._offsetX = 0;
                this._offsetY = 0;

                this._bindEvents();
            }

            _bindEvents() {
                // 開啟
                this.openBtn?.addEventListener('click', () => this.open());
                // 關閉 (按鈕、遮罩、取消鍵)
                this.closeBtn?.addEventListener('click', () => this.close());
                this.overlay?.addEventListener('click', (e) => { if (e.target === this.overlay) this.close(); });
                document.addEventListener('keydown', (e) => { if (e.key === 'Escape' && this.isOpen()) this.close(); });
                // 底部按鈕
                document.getElementById('confirmBtn')?.addEventListener('click', () => this.onConfirm());
                document.getElementById('cancelBtn')?.addEventListener('click', () => this.onCancel());

                // 拖曳事件
                this.dragHandle?.addEventListener('mousedown', (e) => this._onDragStart(e));
                document.addEventListener('mousemove', (e) => this._onDragMove(e));
                document.addEventListener('mouseup', () => this._onDragEnd());
            }

            open() {
                this.overlay.classList.add('open');
                document.body.style.overflow = 'hidden'; // 防止背景捲動
                // 置中 (若非 CSS 置中)
                this._centerModal();
            }

            close() {
                this.overlay.classList.remove('open');
                document.body.style.overflow = '';
            }

            isOpen() { return this.overlay.classList.contains('open'); }

            _centerModal() {
                // CSS flex 已置中,若需手動計算:
                // this.modal.style.top = (window.innerHeight - this.modal.offsetHeight) / 2 + 'px';
                // this.modal.style.left = (window.innerWidth - this.modal.offsetWidth) / 2 + 'px';
            }

            _onDragStart(e) {
                if (e.target === this.closeBtn) return; // 點關閉鈕不拖曳
                this._dragging = true;
                const rect = this.modal.getBoundingClientRect();
                this._offsetX = e.clientX - rect.left;
                this._offsetY = e.clientY - rect.top;
                this.modal.style.transition = 'none'; // 拖曳時關閉動畫
                this.dragHandle.style.cursor = 'grabbing';
                e.preventDefault(); // 防止文字選取
            }

            _onDragMove(e) {
                if (!this._dragging) return;
                const x = e.clientX - this._offsetX;
                const y = e.clientY - this._offsetY;

                // 邊界限制
                const maxX = window.innerWidth - this.modal.offsetWidth;
                const maxY = window.innerHeight - this.modal.offsetHeight;
                const clampedX = Math.max(0, Math.min(x, maxX));
                const clampedY = Math.max(0, Math.min(y, maxY));

                this.modal.style.left = clampedX + 'px';
                this.modal.style.top = clampedY + 'px';
                this.modal.style.margin = '0'; // 覆蓋 CSS 置中 margin
            }

            _onDragEnd() {
                if (!this._dragging) return;
                this._dragging = false;
                this.modal.style.transition = ''; // 恢復動畫
                this.dragHandle.style.cursor = 'move';
            }
        }

        // 初始化
        document.addEventListener('DOMContentLoaded', () => {
            new DraggableModal({
                onConfirm: () => { alert('確定被點擊'); },
                onCancel: () => { alert('取消被點擊'); }
            });
        });
    </script>
</body>
</html>

核心邏輯拆解

1. 拖曳座標計算

// 滑鼠按下時:記錄滑鼠相對視窗左上角的偏移
this._offsetX = e.clientX - modalRect.left;
this._offsetY = e.clientY - modalRect.top;

// 移動時:新位置 = 滑鼠當前位置 - 偏移量
const x = e.clientX - this._offsetX;
const y = e.clientY - this._offsetY;

// 邊界鉗制
const clampedX = Math.max(0, Math.min(x, window.innerWidth - modalWidth));

2. 事件分離與效能

  • `mousedown` 綁在 `dragHandle` (標題列)。
  • `mousemove`/`mouseup` 綁在 `document`,確保滑鼠移出視窗仍能繼續拖曳/釋放。
  • 拖曳時暫停 CSS `transition`,避免位置抖動。

3. 無障礙 (a11y) 細節

  • `role="dialog" aria-modal="true"` 標識模態對話框。
  • `aria-labelledby="modalTitle"` 關聯標題。
  • 關閉按鈕 `aria-label="關閉"`。
  • 焦點管理:開啟時將焦點移至首個可聚焦元素 (如關閉按鈕或確定鍵);關閉時歸還焦點給觸發按鈕。

4. 焦點管理增強 (補充代碼)

open() {
    this.overlay.classList.add('open');
    document.body.style.overflow = 'hidden';
    this._lastFocused = document.activeElement; // 記錄開啟前焦點
    // 延遲聚焦至關閉按鈕 (或第一個輸入框)
    requestAnimationFrame(() => this.closeBtn?.focus());
}

close() {
    this.overlay.classList.remove('open');
    document.body.style.overflow = '';
    this._lastFocused?.focus(); // 歸還焦點
}

進階擴充建議

  • 多層 Modal 堆疊:維護 z-index 遞增、ESC 只關最上層、遮罩層級隔離。
  • 動態內容載入:`open(url)` → `fetch` → 填入 `modal-body` → 顯示。
  • 表單驗證整合:確定鍵觸發 `
    `。
  • 響應式:行動裝置改為底部彈出 (Bottom Sheet),拖曳改為上拉手柄。

總結

原生 JS 實作可拖曳 Modal 核心在於:滑鼠事件三部曲 (down/move/up) + 座標換算 + 邊界鉗制 + CSS 過渡控制。採用 Class 封裝、事件委派、無障礙屬性,即可得到生產級可維護元件,零依賴、體積極小、完全可控。

copyright © 萬盛學電腦網 all rights reserved