到目前为止(2022年10月),所有的答案都建议在打开模态框/弹出窗口时动态地将
overflow: hidden
添加到“body”或“html”中。如果“html”或“body”实际上是您的滚动元素,并且修复了
position: fixed
元素的有些反直觉的过度滚动行为,则此方法有效。
我尝试使用
overscroll-behavior来解决这个问题,这可能有效,但需要在您的模态框中使用可滚动元素(具有实际溢出),如果用户只是决定在“锁定”的元素之外触摸您的覆盖层,则不太可靠。
根据您的页面设计,还有另一种选项,需要将内容和覆盖层分开,并将“html”和“body”的高度明确设置为100%。以下是一个完整的示例:
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
* {
box-sizing: border-box;
}
body {
position: relative;
margin: 0;
padding: 0;
font-family: sans-serif;
font-size: 16px;
}
.content {
padding: 32px;
border: 1px solid #000;
}
.overlay {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(255, 255, 255, .5);
backdrop-filter: blur(5px);
display: flex;
justify-content: center;
align-items: center;
z-index: 1001;
}
.info-box {
background: #000;
color: #eee;
border-radius: 5px;
width: 240px;
height: 240px;
padding: 16px;
}
html, body {
height: 100%;
}
.content {
max-height: 100%;
overflow-y: auto;
}
</style>
</head>
<body>
<div class="content">
<h2>Overlay Background Scroll Test</h2>
<p>Use a window size of around 320x480 for optimal testing (e.g. via device-toolbar).</p>
<h3>Scrollable Page</h3>
<p>Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua.</p>
<p>At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.</p>
<p>Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua.</p>
<button onclick="document.querySelector('.overlay').style.display='flex';">open</button>
</div>
<div class="overlay">
<div class="scroll-fix">
<div class="info-box">
<h3>Pop-Up Message</h3>
<p>Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua.</p>
<button onclick="document.querySelector('.overlay').style.display='none';">close</button>
</div>
</div>
</div>
</body>
重要的部分是最后一个 CSS 条目。这将使您的
.content
元素成为主滚动元素:
html, body {
height: 100%;
}
.content {
max-height: 100%;
overflow-y: auto;
}
这种方法的缺点是:大多数移动浏览器将无法通过滚动自动隐藏其URL栏,因为这似乎取决于
html
或
body
元素的滚动 :-(。