在特定容器元素上覆蓋半透明遮罩,常用於加載狀態、模態交互、元素鎖定等場景。
/**
* 為指定元素添加遮罩層
* @param {string|Element|jQuery} target - 目標元素選擇器/DOM/jQuery對象
* @param {Object} options - 配置選項
*/
function addMask(target, options) {
var $target = $(target);
if (!$target.length) return;
var opts = $.extend({
bgColor: '#000',
opacity: 0.5,
zIndex: 1000,
className: 'custom-mask',
onClick: null // 點擊遮罩回調
}, options);
// 確保目標元素可定位
var position = $target.css('position');
if (position === 'static') {
$target.css('position', 'relative');
}
// 創建遮罩元素
var $mask = $('').css({
position: 'absolute',
top: 0,
left: 0,
width: '100%',
height: '100%',
backgroundColor: opts.bgColor,
opacity: opts.opacity,
zIndex: opts.zIndex,
display: 'none' // 初始隱藏
});
// 綁定點擊事件
if (typeof opts.onClick === 'function') {
$mask.on('click', opts.onClick);
}
// 插入到目標元素內部(首個子元素前)
$target.prepend($mask);
// 返回控制接口
return {
show: function() { $mask.fadeIn(200); },
hide: function() { $mask.fadeOut(200); },
toggle: function() { $mask.fadeToggle(200); },
remove: function() { $mask.remove(); },
$mask: $mask
};
}
// 基礎用法
var mask = addMask('#content-area', {
bgColor: '#808080',
opacity: 0.3,
zIndex: 300
});
// 顯示遮罩(如 AJAX 請求開始時)
mask.show();
// 隱藏遮罩(請求完成時)
setTimeout(function() {
mask.hide();
}, 2000);
// 進階:帶加載動畫的遮罩
var loadingMask = addMask('#data-table', {
bgColor: '#fff',
opacity: 0.7,
zIndex: 500,
className: 'loading-mask'
});
// 自定義遮罩內容(加載圖標+文字)
loadingMask.$mask.html(
'' +
' ' +
' 數據加載中...' +
'' +
''
);
// 使用
$('#refresh-btn').click(function() {
loadingMask.show();
fetchData().always(function() { loadingMask.hide(); });
});
function createGlobalMask(options) {
var opts = $.extend({
bgColor: '#000',
opacity: 0.5,
zIndex: 9999,
className: 'global-mask'
}, options);
var $mask = $('').css({
position: 'fixed',
top: 0,
left: 0,
width: '100%',
height: '100%',
backgroundColor: opts.bgColor,
opacity: opts.opacity,
zIndex: opts.zIndex,
display: 'none'
}).appendTo('body');
return {
show: function(cb) { $mask.fadeIn(200, cb); },
hide: function(cb) { $mask.fadeOut(200, cb); },
$mask: $mask
};
}
// CSS 動畫優化(推薦用 CSS 控制顯隱)
/*
.global-mask {
transition: opacity 0.2s ease;
opacity: 0;
pointer-events: none;
}
.global-mask.show {
opacity: 0.5;
pointer-events: auto;
}
*/
| 問題 | 原因 | 解決方案 |
|---|---|---|
| 遮罩不覆蓋絕對定位子元素 | z-index 層級不足 | 提高遮罩 z-index,或調整子元素 z-index |
| 目標元素無滾動條時遮罩高度不全 | height:100% 相對內容高度 | 目標元素加 overflow:hidden/auto,或用 fixed 定位 |
| 遮罩閃爍/重複創建 | 重複調用未銷毀舊遮罩 | 維護單例模式,或創建前先移除同類遮罩 |
| 表單元素穿透遮罩獲取焦點 | 瀏覽器原生行為 | 遮罩層添加 tabindex="-1" 或點擊時 blur() |
純 CSS 實現更高性能、無 JS 依賴:
.mask-container {
position: relative;
}
.mask-container::before {
content: '';
position: absolute;
inset: 0;
background: rgba(0,0,0,0.5);
z-index: 10;
opacity: 0;
pointer-events: none;
transition: opacity 0.2s;
}
.mask-container.masked::before {
opacity: 1;
pointer-events: auto;
}
// JS 只需切換 class
$('#container').addClass('masked'); // 顯示
$('#container').removeClass('masked'); // 隱藏