js遮罩实现
遮罩实现方法
在JavaScript中,遮罩(Mask)通常用于覆盖页面或部分元素,阻止用户交互或突出显示特定内容。以下是几种常见的实现方式:
使用CSS和HTML结构
创建一个覆盖全屏的遮罩层,通过CSS控制样式和显示状态:

<div id="mask" class="mask"></div>
.mask {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.5);
z-index: 999;
display: none;
}
// 显示遮罩
document.getElementById('mask').style.display = 'block';
// 隐藏遮罩
document.getElementById('mask').style.display = 'none';
动态创建遮罩元素
通过JavaScript动态生成遮罩元素并插入DOM:
function createMask() {
const mask = document.createElement('div');
mask.id = 'dynamic-mask';
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.7)';
mask.style.zIndex = '1000';
document.body.appendChild(mask);
return mask;
}
结合模态框使用
遮罩常与模态框(Modal)配合使用,点击遮罩关闭模态框:

const mask = document.getElementById('mask');
mask.addEventListener('click', function() {
document.getElementById('modal').style.display = 'none';
this.style.display = 'none';
});
高级遮罩效果
添加CSS过渡效果增强用户体验:
.mask {
opacity: 0;
transition: opacity 0.3s ease;
}
.mask.active {
opacity: 1;
}
// 显示带过渡效果的遮罩
document.getElementById('mask').classList.add('active');
局部遮罩实现
为特定元素创建局部遮罩:
function createLocalMask(element) {
const rect = element.getBoundingClientRect();
const mask = document.createElement('div');
mask.style.position = 'absolute';
mask.style.top = `${rect.top}px`;
mask.style.left = `${rect.left}px`;
mask.style.width = `${rect.width}px`;
mask.style.height = `${rect.height}px`;
mask.style.backgroundColor = 'rgba(0, 0, 0, 0.3)';
document.body.appendChild(mask);
return mask;
}
以上方法可根据具体需求选择使用,通过调整CSS属性和JavaScript逻辑可以实现各种遮罩效果。






