学习链接:蒙层禁止页面滚动的方案
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>蒙层禁止页面滚动的方案</title>
<style type="text/css">
#mask{
position: fixed;
height: 100vh;
width: 100vw;
background: rgba(0, 0, 0, 0.6);
top: 0;
left: 0;
display: flex;
align-items: center;
justify-content: center;
}
.hide{
display: none !important;
}
.long-content > div{
height: 300px;
}
.mask-content{
width: 300px;
height: 100px;
overflow-x: auto;
background: #fff;
}
.mask-content > div{
height: 300px;
}
</style>
</head>
<body>
<div class="long-content">
<div>long content</div>
<div>long content</div>
<div>long content</div>
<button id="btn">弹窗</button>
<div>long content</div>
<div>long content</div>
<div>long content</div>
<div>long content</div>
</div>
<div id="mask" class="hide">
<div class="mask-content">
<div>mask-content</div>
<div>mask-content</div>
<div>mask-content</div>
<div>mask-content</div>
<div>mask-content</div>
<div>mask-content</div>
<div>mask-content</div>
<div>mask-content</div>
<div>mask-content</div>
</div>
</div>
</body>
<script type="text/javascript">
(() => {
const btn = document.getElementById("btn");
const mask = document.getElementById("mask");
const maskContent = document.querySelector(".mask-content");
const body = document.body;
let documentTop = 0; // 记录按下按钮时的 `top`
/* 按钮点击时: 1. 给mask添加display:none;
2. 记录此时页面被卷去的高度(记录滚动位置)
3. 给body加上fixed固定定位(此时,如果不做任何处理,页面会立即滚动到top:0的位置);
4. 将页面滚动到之前记录的位置(恢复弹窗前的位置)
*/
btn.addEventListener("click", e => {
mask.classList.remove("hide");
documentTop = document.scrollingElement.scrollTop;
body.style.position = "fixed"
body.style.top = -documentTop + "px";
})
/* 点击蒙层时: 1. 给mask添加hide样式类, 让mask的display为none
2. 恢复body的默认定位(此时,如果不做任何处理,页面又会立即滚动到top:0的位置)
3. 将页面滚动到之前记录的位置(恢复弹窗前的位置)
*/
mask.addEventListener("click", e => {
mask.classList.add("hide");
body.style.position = "static";
body.style.top = "auto";
document.scrollingElement.scrollTop = documentTop;
})
/* 阻止事件冒泡, 防止点击弹框中的内容时, 也把弹框关闭了 */
maskContent.addEventListener('click',(e) => {
e.stopPropagation();
})
})();
</script>
</html>