點擊觸發後,頁面被半透明黑色遮罩覆蓋,目標元素「突出」顯示在遮罩之上,用於新手引導、功能聚焦、圖片預覽、重要提示等場景。
<script>
$(function() {
// 獲取文檔高度 (包含滾動區域)
var docHeight = $(document).height();
// 創建遮罩層
$("body").append("<div id='overlay'></div>");
// 設置遮罩樣式
$("#overlay")
.height(docHeight)
.css({
'opacity': 0.4,
'position': 'absolute',
'top': 0,
'left': 0,
'background-color': 'black',
'width': '100%',
'z-index': 5000
});
});
</script>
| 問題 | 原文代碼 | 修復方案 |
|---|---|---|
| 滾動時遮罩不覆蓋可視區 | position: absolute + $(document).height() | 改用 position: fixed + width: 100%; height: 100vh |
| 遮罩阻擋目標元素交互 | 目標元素 z-index < 5000 | 目標元素 position: relative; z-index: 5001 |
| 重複點擊創建多個遮罩 | 無防重複邏輯 | 檢查 $('#overlay').length 或單例模式 |
| 無關閉機制 | 只創建不銷毀 | 提供 close() 方法,點擊遮罩/ESC 關閉 |
| 動態內容高度變化 | 固定高度 | fixed 定位自適應,或監聽 resize 更新 |
class ModalHighlight {
constructor(options = {}) {
this.options = Object.assign({
overlayColor: 'rgba(0, 0, 0, 0.5)',
overlayZIndex: 9999,
targetZIndex: 10000,
animationDuration: 300,
closeOnOverlayClick: true,
closeOnEsc: true,
onOpen: null,
onClose: null
}, options);
this.$overlay = null;
this.$target = null;
this.isOpen = false;
this._boundHandlers = {};
}
open(targetSelector) {
if (this.isOpen) return Promise.resolve();
this.$target = $(targetSelector).first();
if (!this.$target.length) {
return Promise.reject(new Error('Target element not found'));
}
return new Promise((resolve) => {
this._createOverlay();
this._positionTarget();
this._bindEvents();
this._animateIn(() => {
this.isOpen = true;
this.options.onOpen?.(this.$target);
resolve();
});
});
}
close() {
if (!this.isOpen) return Promise.resolve();
return new Promise((resolve) => {
this._animateOut(() => {
this._cleanup();
this.isOpen = false;
this.options.onClose?.(this.$target);
resolve();
});
});
}
_createOverlay() {
this.$overlay = $('')
.css({
position: 'fixed',
top: 0, left: 0,
width: '100%', height: '100%',
backgroundColor: this.options.overlayColor,
zIndex: this.options.overlayZIndex,
display: 'none' // 先隱藏,動畫顯示
})
.appendTo('body');
}
_positionTarget() {
// 確保目標元素可定位
const pos = this.$target.css('position');
if (pos === 'static') {
this.$target.css('position', 'relative');
}
this.$target.css('zIndex', this.options.targetZIndex);
// 可選:添加高亮邊框/陰影
this.$target.data('originalOutline', this.$target.css('outline'))
.css('outline', '3px solid #fff')
.css('boxShadow', '0 0 20px rgba(255,255,255,0.5)');
}
_bindEvents() {
if (this.options.closeOnOverlayClick) {
this._boundHandlers.overlayClick = () => this.close();
this.$overlay.on('click', this._boundHandlers.overlayClick);
}
if (this.options.closeOnEsc) {
this._boundHandlers.keydown = (e) => {
if (e.key === 'Escape') this.close();
};
$(document).on('keydown', this._boundHandlers.keydown);
}
}
_animateIn(callback) {
this.$overlay.fadeIn(this.options.animationDuration, callback);
}
_animateOut(callback) {
this.$overlay.fadeOut(this.options.animationDuration, () => {
callback();
});
}
_cleanup() {
// 恢復目標樣式
if (this.$target) {
this.$target.css({
zIndex: '',
outline: this.$target.data('originalOutline') || '',
boxShadow: ''
}).removeData('originalOutline');
}
// 移除事件
Object.values(this._boundHandlers).forEach(handler => {
this.$overlay?.off('click', handler);
$(document).off('keydown', handler);
});
this._boundHandlers = {};
// 移除遮罩
this.$overlay?.remove();
this.$overlay = null;
this.$target = null;
}
}
// 單例模式便於全局調用
window.highlight = new ModalHighlight();
// 使用示例
$('#guideBtn').click(() => highlight.open('#feature-box'));
$('#closeGuide').click(() => highlight.close());
CSS 替代方案 (無 JS 依賴,純 CSS 模態)
<style>
.modal-highlight {
position: fixed;
inset: 0;
background: rgba(0,0,0,0.5);
z-index: 9999;
display: flex;
align-items: center;
justify-content: center;
opacity: 0;
pointer-events: none;
transition: opacity 0.3s;
}
.modal-highlight:target {
opacity: 1;
pointer-events: auto;
}
.modal-highlight .target {
position: relative;
z-index: 10000;
outline: 3px solid white;
box-shadow: 0 0 30px rgba(255,255,255,0.6);
animation: pulse 2s infinite;
}
@keyframes pulse {
0%, 100% { box-shadow: 0 0 20px rgba(255,255,255,0.5); }
50% { box-shadow: 0 0 40px rgba(255,255,255,0.8); }
}
</style>
<!-- HTML -->
<a href="#guide1">開始引導</a>
<div id="guide1" class="modal-highlight">
<div class="target">目標內容</div>
<a href="#" class="close-btn">× 關閉</a>
</div>
無障礙性增強 (WCAG 2.1)
// 在 open() 中添加
this.$overlay.attr('role', 'dialog')
.attr('aria-modal', 'true')
.attr('aria-labelledby', 'highlight-title');
// 目標元素添加
this.$target.attr('id', 'highlight-title')
.attr('tabindex', '-1')
.focus(); // 焦點移入
// 焦點陷阱 (簡易版)
this._boundHandlers.focusTrap = (e) => {
if (e.key === 'Tab') {
const focusable = this.$overlay.find('button, a, input, [tabindex]:not([tabindex="-1"])').get();
const first = focusable[0], last = focusable[focusable.length-1];
if (e.shiftKey && document.activeElement === first) {
e.preventDefault(); last.focus();
} else if (!e.shiftKey && document.activeElement === last) {
e.preventDefault(); first.focus();
}
}
};
$(document).on('keydown', this._boundHandlers.focusTrap);
總結
頁面遮罩高亮是引導用戶注意力的有效手段。核心要點:**fixed 定位覆蓋全視口、z-index 層級管理、目標元素相對定位提層、動畫過渡、完整的生命週期管理 (打開/關閉/清理)**。現代項目建議封裝為可復用組件,支持 Promise、無障礙、動態內容適配。