1.首先呢我们需要创建html结构和css操作,如下所示:
<!DOCTYPE html>
<html>
<head>
<title></title>
<style>
.mask {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.5);
display: none;
}
.content {
position: relative;
z-index: 999;
}
</style>
</head>
<body>
<div class="mask"></div>
<div class="content">
//这里是内容区
</div>
</body>
</html>
2.接下来呢我们需要使用js来控制遮罩层的显示隐藏以及页面的滚动行为,如下所示:
// 获取遮罩层和内容容器元素
const mask = document.querySelector('.mask');
const content = document.querySelector('.content');
// 显示遮罩层并禁止页面滚动
function showMask() {
// 添加样式使遮罩层显示
mask.style.display = 'block';
// 计算滚动条的偏移量
const scrollY = window.scrollY;
// 设置内容容器的样式,固定在当前位置
content.style.top = `-${scrollY}px`;
// 禁止页面滚动
document.body.style.overflow = 'hidden';
}