萬盛學電腦網

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

原生 JavaScript 實現可拖拽、遮罩層、居中顯示的 DIV 彈出層組件

功能特性

  • 純原生 JS,零依賴,輕量級
  • 彈出層螢幕居中(含滾動條偏移計算)
  • 半透明黑色遮罩層,鎖定背景滾動
  • 標題欄拖拽移動彈窗
  • 關閉按鈕銷毀遮罩並恢復頁面滾動

核心 JS 實現

/**
 * 彈出層控制器
 * @param {string} layerId - 彈出層容器 ID
 * @param {string} handleId - 拖拽手柄 ID(通常為標題欄)
 */
function Dialog(layerId, handleId) {
  this.layer = document.getElementById(layerId);
  this.handle = document.getElementById(handleId);
  this.mask = null;
  this._dragData = { x: 0, y: 0 };
  this._initEvents();
}

Dialog.prototype = {
  _initEvents: function() {
    var self = this;
    // 拖拽:按下手柄
    this.handle.onmousedown = function(e) {
      e = e || window.event;
      self._dragData.x = e.clientX - self.layer.offsetLeft;
      self._dragData.y = e.clientY - self.layer.offsetTop;
      document.onmousemove = function(ev) { self._onDrag(ev); };
      document.onmouseup = function() { self._stopDrag(); };
      return false; // 防止文字選中
    };
  },

  _onDrag: function(e) {
    e = e || window.event;
    this.layer.style.left = (e.clientX - this._dragData.x) + 'px';
    this.layer.style.top  = (e.clientY - this._dragData.y) + 'px';
  },

  _stopDrag: function() {
    document.onmousemove = null;
    document.onmouseup = null;
  },

  // 顯示彈窗並建立遮罩
  show: function() {
    // 1. 居中定位
    var cw = document.documentElement.clientWidth;
    var ch = document.documentElement.clientHeight;
    var sl = document.documentElement.scrollLeft || document.body.scrollLeft;
    var st = document.documentElement.scrollTop  || document.body.scrollTop;

    this.layer.style.left = (cw - this.layer.offsetWidth) / 2 + sl + 'px';
    this.layer.style.top  = (ch - this.layer.offsetHeight) / 2 + st - 50 + 'px'; // 略微向上
    this.layer.style.display = 'block';

    // 2. 建立遮罩層
    this.mask = document.createElement('div');
    this.mask.id = 'dialogMask';
    Object.assign(this.mask.style, {
      position: 'fixed',
      top: 0, left: 0,
      width: '100%', height: '100%',
      background: '#000',
      opacity: '0.6',
      filter: 'alpha(opacity=60)', // IE8-
      zIndex: 500
    });
    document.body.appendChild(this.mask);
    document.body.style.overflow = 'hidden'; // 鎖定滾動

    // 3. 確保彈窗在遮罩之上
    this.layer.style.zIndex = 1000;
  },

  // 關閉彈窗並清理
  close: function() {
    this.layer.style.display = 'none';
    document.body.style.overflow = 'auto';
    if (this.mask && this.mask.parentNode) {
      this.mask.parentNode.removeChild(this.mask);
      this.mask = null;
    }
  }
};

// 實例化
var myDialog = new Dialog('myDialog', 'dialogHandle');

HTML 結構

<!-- 彈出層容器:預設隱藏,絕對定位 -->
<div id="myDialog" style="display:none; position:absolute; z-index:1000; background:#67a3d9; padding:20px; width:400px; border-radius:4px;">
  <!-- 拖拽手柄(標題欄) -->
  <div id="dialogHandle" style="cursor:move; padding:5px 10px; background:#4a8bc2; color:#fff; margin:-20px -20px 15px; border-radius:4px 4px 0 0;">
    標題欄 - 按住拖拽移動
  </div>

  <p>這裡放置彈窗內容,可包含表單、圖片、文字等任意 HTML。</p>

  <button onclick="myDialog.close()" style="margin-top:10px; padding:6px 16px;">關閉彈窗</button>
</div>

<!-- 觸發按鈕 -->
<button onclick="myDialog.show()">打開彈出層</button>

CSS 美化建議(可加入樣式表)

#myDialog {
  box-shadow: 0 4px 12px rgba(0,0,0,0.3);
  font-family: 'Microsoft YaHei', sans-serif;
}
#dialogHandle {
  user-select: none; /* 禁止選中文字 */
}
#dialogMask {
  transition: opacity 0.2s;
}

進階擴展方向

  • 支持 ESC 鍵關閉、點擊遮罩關閉
  • 多實例管理(彈窗堆疊 z-index 遞增)
  • 動畫過渡(fade-in/out、slide-down)
  • 響應式寬度、最大高度滾動
  • 模組化輸出(ESM/CommonJS/UMD)
copyright © 萬盛學電腦網 all rights reserved