萬盛學電腦網

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

JavaScript 實現頁面遮罩層:支援 iframe、堆疊計數與自適應調整

需求場景

  • AJAX 載入時顯示遮罩,防止重複提交
  • 模態彈窗背景遮罩
  • 跨 iframe 頁面遮罩(主頁面遮罩 iframe 內容)
  • 多重遮罩堆疊管理(開啟 N 次,關閉 N 次才真正移除)

核心實作

var maskStackCount = 0;

/**
 * 頁面遮罩控制
 * @param {'open'|'close'} method - 操作類型,預設 'open'
 */
function mask(method) {
  method = method || 'open';
  
  // 目標窗口:這裡針對 iframe,也可用 $(window) 或 $('body')
  var winObj = window.top.$('body').find("iframe[name='dialognormaliframe']");
  
  if (method === 'open') {
    if (maskStackCount <= 0) {
      // 建立遮罩元素
      var $mask = $('')
        .appendTo('body');
      
      // 設定尺寸覆蓋目標窗口
      $mask.css({
        width: winObj.width() + 'px',
        height: winObj.height() + 'px',
        filter: 'alpha(opacity=60)',  // IE8 相容
        opacity: 0.6,
        background: '#000',
        position: 'absolute',
        top: 0,
        left: 0,
        zIndex: 9999
      }).show();
      
      // 視窗縮放時自適應調整
      winObj.on('resize.mask', function() {
        $mask.css({
          width: winObj.width() + 'px',
          height: winObj.height() + 'px'
        });
      });
    }
    maskStackCount++;
  } 
  else if (method === 'close') {
    maskStackCount--;
    if (maskStackCount <= 0) {
      $('#window-mask').remove();
      winObj.off('resize.mask');
      maskStackCount = 0;  // 保護歸零
    }
  }
}

CSS 樣式建議

.window-mask {
  position: fixed;  /* 相對 viewport 定位,不受滾動影響 */
  top: 0; left: 0; right: 0; bottom: 0;
  background: rgba(0, 0, 0, 0.5);  /* 現代瀏覽器半透明 */
  z-index: 9999;
  display: none;
}

/* IE8 降級 */
.ie8 .window-mask {
  background: #000;
  filter: alpha(opacity=50);
}

使用範例

// AJAX 請求前開啟,完成後關閉
function loadData() {
  mask('open');
  $.ajax({
    url: '/api/data',
    success: function(res) { render(res); },
    complete: function() { mask('close'); }
  });
}

// 巢狀調用:外層開啟,內層也開啟,只有外層關閉時才移除
function outer() {
  mask('open');
  inner();
  mask('close');
}

function inner() {
  mask('open');
  // do something
  mask('close');
}

進階增強:Loading 圖示與訊息

function mask(method, options) {
  options = $.extend({
    message: '載入中...',
    spinner: true
  }, options);
  
  if (method === 'open') {
    if (maskStackCount <= 0) {
      var $mask = $('
').appendTo('body'); var $content = $('
').appendTo($mask); if (options.spinner) { $content.append('
'); } $content.append('
' + options.message + '
'); // 置中 $content.css({ position: 'absolute', top: '50%', left: '50%', transform: 'translate(-50%, -50%)', color: '#fff', textAlign: 'center' }); // ... 尺寸調整邏輯同前 } maskStackCount++; } else { // ... 關閉邏輯同前 } } // 使用 mask('open', { message: '資料儲存中,請稍候...' });

注意事項

  • z-index 層級管理:遮罩 z-index 需低於彈窗,建議建立分層常數
  • iframe 跨域限制:若 iframe 跨域,winObj.width() 會報錯,需用 postMessage 通訊或改遮罩父頁面
  • 記憶體洩漏防護:堆疊計數器必須配對,異常時用 try/finally 確保關閉
  • 移動端觸摸穿透:遮罩層添加 touch-action: none 或監聽 touchmove 阻止預設

現代替代:CSS-only 遮罩

<div class="modal-overlay" id="overlay">
  <div class="modal-content">...</div>
</div>

.modal-overlay {
  position: fixed; inset: 0;
  background: rgba(0,0,0,0.5);
  display: flex; align-items: center; justify-content: center;
  opacity: 0; visibility: hidden; transition: 0.3s;
  z-index: 1000;
}
.modal-overlay.active { opacity: 1; visibility: visible; }

// JS 只需切換 class
$('#overlay').addClass('active');  // 開啟
$('#overlay').removeClass('active');  // 關閉

總結

堆疊計數器模式解決多重遮罩管理問題,配合 resize 事件自適應、iframe 目標鎖定,構建健壯的遮罩工具函數。現代專案建議採用 CSS-driven 方案,JS 僅負責狀態切換,關注點分離更清晰。

copyright © 萬盛學電腦網 all rights reserved