萬盛學電腦網

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

原生 JS 實現可拖拽彈窗 + 遮罩層(無依賴)

不依賴任何庫,純原生 JS 實現帶遮罩的模態彈窗,支援拖拽移動、點擊遮罩關閉、自適應視窗邊界限制。

核心功能函數

// 顯示彈窗
function popDivShow(popDivId, dragDivId, isShowMask) {
  if (isShowMask) createMask(popDivId);
  var box = document.getElementById(popDivId);
  var handle = document.getElementById(dragDivId);
  box.style.display = 'block';

  handle.onmousedown = function(e) {
    e = e || window.event;
    var disX = e.clientX - box.offsetLeft;
    var disY = e.clientY - box.offsetTop;
    var dragging = true;

    handle.setCapture && handle.setCapture();

    document.onmousemove = function(e) {
      if (!dragging) return;
      e = e || window.event;
      var l = e.clientX - disX;
      var t = e.clientY - disY;
      var maxL = document.documentElement.clientWidth - box.offsetWidth;
      var maxT = document.documentElement.clientHeight - box.offsetHeight;
      l = Math.max(0, Math.min(l, maxL));
      t = Math.max(0, Math.min(t, maxT));
      box.style.margin = 0;
      box.style.left = l + 'px';
      box.style.top = t + 'px';
      return false;
    };

    document.onmouseup = handle.onlosecapture = function() {
      dragging = false;
      handle.releaseCapture && handle.releaseCapture();
      document.onmousemove = document.onmouseup = null;
    };
    return false;
  };
}

// 建立遮罩
function createMask(popDivId) {
  var mask = document.createElement('div');
  mask.id = 'maskDiv';
  Object.assign(mask.style, {
    position: 'fixed', top: 0, left: 0, width: '100%',
    height: (document.body.scrollHeight + 50) + 'px',
    backgroundColor: '#333', opacity: 0.7,
    filter: 'alpha(opacity=70)', zIndex: getZindex(popDivId) - 1
  });
  mask.onmousedown = function() {
    document.body.removeChild(this);
    popDivHidden(popDivId);
  };
  document.body.appendChild(mask);
}

// 隱藏彈窗並移除遮罩
function popDivHidden(popDivId) {
  document.getElementById(popDivId).style.display = 'none';
  var mask = document.getElementById('maskDiv');
  mask && mask.parentNode.removeChild(mask);
}

function getZindex(popDivId) {
  return document.getElementById(popDivId).style.zIndex || 1000;
}

使用方式

<div id="popup" style="display:none;position:absolute;z-index:1000;">
  <div id="popupTitle">標題欄(可拖拽)</div>
  <div>彈窗內容...</div>
</div>
<button onclick="popDivShow('popup','popupTitle',true)">打開彈窗</button>

現代化改造提示

  • 使用 addEventListener 替代 onmousedown 等屬性,避免事件覆蓋。
  • 拖拽邏輯可改用 pointerdown/pointermove/pointerup 統一處理滑鼠/觸控。
  • 遮罩插入 document.body 即可,無需 window.parent(除非在 iframe 內)。
copyright © 萬盛學電腦網 all rights reserved