js 实现遮罩
使用 CSS 和 JavaScript 创建遮罩层
遮罩层通常用于模态框、加载提示或页面覆盖场景。以下是几种实现方式:
基础遮罩层实现
通过动态创建 div 元素作为遮罩:

function createMask() {
const mask = document.createElement('div');
mask.style.position = 'fixed';
mask.style.top = '0';
mask.style.left = '0';
mask.style.width = '100%';
mask.style.height = '100%';
mask.style.backgroundColor = 'rgba(0,0,0,0.5)';
mask.style.zIndex = '1000';
document.body.appendChild(mask);
return mask;
}
// 调用创建
const mask = createMask();
// 移除遮罩
mask.remove();
带交互的遮罩层
点击遮罩关闭功能:
function createClosableMask(closeCallback) {
const mask = document.createElement('div');
mask.style.cssText = `
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0,0,0,0.7);
z-index: 1000;
cursor: pointer;
`;
mask.addEventListener('click', () => {
mask.remove();
if (closeCallback) closeCallback();
});
document.body.appendChild(mask);
return mask;
}
结合 CSS 动画的遮罩
添加淡入淡出效果:

.mask {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0,0,0,0.5);
z-index: 1000;
opacity: 0;
transition: opacity 0.3s;
}
.mask.show {
opacity: 1;
}
JavaScript 控制:
const mask = document.createElement('div');
mask.className = 'mask';
document.body.appendChild(mask);
// 显示遮罩
mask.classList.add('show');
// 隐藏遮罩
mask.classList.remove('show');
阻止滚动穿透
当遮罩显示时禁止页面滚动:
function toggleBodyScroll(enable) {
document.body.style.overflow = enable ? '' : 'hidden';
}
// 显示遮罩时
toggleBodyScroll(false);
// 隐藏遮罩时
toggleBodyScroll(true);
高级封装示例
完整可复用的遮罩组件:
class Mask {
constructor(options = {}) {
this.opacity = options.opacity || 0.5;
this.color = options.color || '#000';
this.zIndex = options.zIndex || 1000;
this.element = null;
}
show() {
if (!this.element) {
this.element = document.createElement('div');
this.element.style.cssText = `
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: ${this.color};
opacity: ${this.opacity};
z-index: ${this.zIndex};
`;
document.body.appendChild(this.element);
}
document.body.style.overflow = 'hidden';
}
hide() {
if (this.element) {
this.element.remove();
this.element = null;
}
document.body.style.overflow = '';
}
}
// 使用示例
const mask = new Mask({ opacity: 0.7 });
mask.show();
// 需要隐藏时调用 mask.hide();
这些方法提供了从简单到复杂的遮罩实现方案,可根据实际需求选择合适的方式。






