萬盛學電腦網

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

原生 JavaScript 實現遮罩層(Modal/彈窗遮罩)完整教程

核心結構

<div id="mask" class="modal-mask"></div>
<div id="dialog" class="modal-dialog">
  <div class="modal-header">標題 <button class="close-btn">×</button></div>
  <div class="modal-body">內容區...</div>
  <div class="modal-footer"><button class="confirm-btn">確定</button></div>
</div>

CSS 關鍵樣式

.modal-mask {
  position: fixed; inset: 0; background: rgba(0,0,0,0.4);
  z-index: 1000; display: none;
  /* 現代瀏覽器 backdrop-filter 模糊背景 */
  backdrop-filter: blur(2px);
}
.modal-dialog {
  position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%);
  width: 500px; max-width: 90vw; max-height: 80vh; overflow: auto;
  background: #fff; border-radius: 8px; box-shadow: 0 4px 20px rgba(0,0,0,.2);
  z-index: 1001; display: none;
}
.modal-dialog.open, .modal-mask.open { display: block; }

ES6 類封裝(支持多實例、拖拽、鍵盤、動畫)

class Modal {
  constructor(options = {}) {
    this.options = Object.assign({
      title: '', content: '', width: '500px',
      onConfirm: null, onCancel: null, onClose: null,
      draggable: true, maskClosable: true, escClosable: true
    }, options);
    this.mask = null;
    this.dialog = null;
    this.init();
  }

  init() {
    // 創建遮罩
    this.mask = document.createElement('div');
    this.mask.className = 'modal-mask';
    document.body.appendChild(this.mask);

    // 創建對話框
    this.dialog = document.createElement('div');
    this.dialog.className = 'modal-dialog';
    this.dialog.style.width = this.options.width;
    this.dialog.innerHTML = `
      
      
      
    `;
    document.body.appendChild(this.dialog);

    this.bindEvents();
    // 強制重排觸發動畫
    requestAnimationFrame(() => this.show());
  }

  bindEvents() {
    // 關閉按鈕
    this.dialog.querySelector('.close-btn').addEventListener('click', () => this.hide('cancel'));
    this.dialog.querySelector('.cancel-btn').addEventListener('click', () => this.hide('cancel'));
    this.dialog.querySelector('.confirm-btn').addEventListener('click', () => this.hide('confirm'));
    
    // 遮罩點擊關閉
    if (this.options.maskClosable) {
      this.mask.addEventListener('click', () => this.hide('mask'));
    }
    // ESC 關閉
    if (this.options.escClosable) {
      this.escHandler = e => { if (e.key === 'Escape') this.hide('esc'); };
      document.addEventListener('keydown', this.escHandler);
    }
    // 拖拽移動
    if (this.options.draggable) this.enableDrag();
    // 滾動時保持居中(fixed 定位無需處理,absolute 才需)
  }

  enableDrag() {
    const header = this.dialog.querySelector('.modal-header');
    let isDragging = false, offsetX = 0, offsetY = 0;
    header.style.cursor = 'move';
    header.addEventListener('mousedown', e => {
      if (e.target.classList.contains('close-btn')) return;
      isDragging = true;
      offsetX = e.clientX - this.dialog.offsetLeft;
      offsetY = e.clientY - this.dialog.offsetTop;
      header.style.userSelect = 'none';
    });
    document.addEventListener('mousemove', e => {
      if (!isDragging) return;
      this.dialog.style.left = (e.clientX - offsetX) + 'px';
      this.dialog.style.top = (e.clientY - offsetY) + 'px';
      this.dialog.style.transform = 'none'; // 拖拽後取消 transform 居中
    });
    document.addEventListener('mouseup', () => { isDragging = false; header.style.userSelect = ''; });
  }

  show() {
    this.mask.classList.add('open');
    this.dialog.classList.add('open');
    // 防止 body 滾動
    document.body.style.overflow = 'hidden';
  }

  hide(action) {
    this.mask.classList.remove('open');
    this.dialog.classList.remove('open');
    document.body.style.overflow = '';
    // 動畫結束後移除 DOM
    setTimeout(() => {
      this.mask.remove();
      this.dialog.remove();
      document.removeEventListener('keydown', this.escHandler);
      if (this.options.onClose) this.options.onClose(action);
      if (action === 'confirm' && this.options.onConfirm) this.options.onConfirm();
      if (action === 'cancel' && this.options.onCancel) this.options.onCancel();
    }, 300); // 與 CSS transition 時間一致
  }

  // 靜態快捷方法
  static alert(content, title = '提示') {
    return new Modal({ title, content, onConfirm: () => {} });
  }
  static confirm(content, title = '確認', onConfirm, onCancel) {
    return new Modal({ title, content, onConfirm, onCancel });
  }
}

// 使用示例
Modal.confirm('確定要刪除該記錄嗎?', '刪除確認', 
  () => console.log('用戶確認刪除'), 
  () => console.log('用戶取消')
);

無障礙 (a11y) 必做項

  • role="dialog"、aria-modal="true"、aria-labelledby="titleId"、aria-describedby="bodyId"。
  • 打開時將焦點移至對話框首個可聚焦元素;關閉時焦點回歸觸發元素。
  • Tab 循環鍵盤陷阱(焦點不離開對話框)。

避坑指南

  • 避免 position: absolute + 滾動居中計算,改用 fixed + transform: translate(-50%, -50%) 自動居中。
  • 動態內容高度超過視口時,對話框內部 overflow:auto,遮罩固定全屏。
  • 多層彈窗管理:維護 z-index 棧或使用單例管理器。
copyright © 萬盛學電腦網 all rights reserved