理论
查看 pinterest 网站的当前实现(将来可能会更改),当您打开叠加层时,noscroll 类应用于body 元素并设置了overflow: hidden,因此body 是不再可滚动。
覆盖(即时创建或已在页面内创建并通过display: block 可见,没有区别)具有position : fixed 和overflow-y: scroll,以及top、left、@987654332 @ 和bottom 属性设置为0:这种样式使覆盖层填充整个视口。
覆盖层内的div 只是在position: static 中,然后您看到的垂直滚动条与该元素相关。因此,内容是可滚动的,但覆盖仍然是固定的。
当您关闭缩放时,您会隐藏叠加层(通过 display: none),然后您也可以通过 javascript 将其完全删除(或者只是其中的内容,由您决定如何注入它)。
作为最后一步,您还必须将 noscroll 类删除到 body(因此溢出属性返回到其初始值)
代码
Codepen Example
(它通过更改覆盖层的aria-hidden 属性来显示和隐藏它并增加其可访问性)。
标记
(打开按钮)
<button type="button" class="open-overlay">OPEN LAYER</button>
(覆盖和关闭按钮)
<section class="overlay" aria-hidden="true">
<div>
<h2>Hello, I'm the overlayer</h2>
...
<button type="button" class="close-overlay">CLOSE LAYER</button>
</div>
</section>
CSS
.noscroll {
overflow: hidden;
}
.overlay {
position: fixed;
overflow-y: scroll;
top: 0; right: 0; bottom: 0; left: 0; }
[aria-hidden="true"] { display: none; }
[aria-hidden="false"] { display: block; }
Javascript (vanilla-JS)
var body = document.body,
overlay = document.querySelector('.overlay'),
overlayBtts = document.querySelectorAll('button[class$="overlay"]');
[].forEach.call(overlayBtts, function(btt) {
btt.addEventListener('click', function() {
/* Detect the button class name */
var overlayOpen = this.className === 'open-overlay';
/* Toggle the aria-hidden state on the overlay and the
no-scroll class on the body */
overlay.setAttribute('aria-hidden', !overlayOpen);
body.classList.toggle('noscroll', overlayOpen);
/* On some mobile browser when the overlay was previously
opened and scrolled, if you open it again it doesn't
reset its scrollTop property */
overlay.scrollTop = 0;
}, false);
});
最后,这是另一个示例,其中覆盖以淡入效果打开,CSS transition 应用于opacity 属性。当滚动条消失时,还应用了padding-right 以避免底层文本重排。
Codepen Example (fade)
CSS
.noscroll { overflow: hidden; }
@media (min-device-width: 1025px) {
/* not strictly necessary, just an experiment for
this specific example and couldn't be necessary
at all on some browser */
.noscroll {
padding-right: 15px;
}
}
.overlay {
position: fixed;
overflow-y: scroll;
top: 0; left: 0; right: 0; bottom: 0;
}
[aria-hidden="true"] {
transition: opacity 1s, z-index 0s 1s;
width: 100vw;
z-index: -1;
opacity: 0;
}
[aria-hidden="false"] {
transition: opacity 1s;
width: 100%;
z-index: 1;
opacity: 1;
}