在JavaScript中实现遮罩层时禁止页面滚动条滚动,通常涉及以下基础概念和技术手段:
click
、scroll
等。body
的高度变化导致的。no-scroll
类时,同时设置height: 100vh;
。no-scroll
类时,同时设置height: 100vh;
。body
的overflow
属性变化导致的。body
的原始样式。<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Overlay Example</title>
<style>
.no-scroll {
overflow: hidden;
height: 100vh;
}
#overlay {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0, 0, 0, 0.5);
display: none;
}
</style>
</head>
<body>
<button onclick="showOverlay()">Show Overlay</button>
<div id="overlay" onclick="hideOverlay()"></div>
<script>
function showOverlay() {
document.getElementById('overlay').style.display = 'block';
document.body.classList.add('no-scroll');
}
function hideOverlay() {
document.getElementById('overlay').style.display = 'none';
document.body.classList.remove('no-scroll');
}
</script>
</body>
</html>
通过上述方法,你可以有效地在显示遮罩层时禁止页面滚动,并在关闭遮罩层时恢复页面滚动。
领取专属 10元无门槛券
手把手带您无忧上云