查看pinterest网站的当前实现(将来可能会更改),当您打开叠加层时,会将一个noscroll
类应用于该body
元素并overflow:hidden
进行设置,因此该类body
不再可滚动。
叠加(上即时或已经在页面内,并通过可见创建display: block
,它使没有区别)有position : fixed
和overflow-y: scroll
,与top
,left
,right
和bottom
属性设置为0
:这种风格使得覆盖填充整个视口。
该div
覆盖里面,而不是仅仅在position: static
然后就看到垂直滚动条是有关该元素。结果,内容是可滚动的,但是覆盖层保持固定。
关闭缩放时,您可以隐藏叠加层(通过display: none
),然后也可以通过javascript完全删除叠加层(或仅删除其中的内容,具体取决于注入方式)。
作为最后一步,您还必须将noscroll
类删除到body
(这样,溢出属性将返回其初始值)
(它通过更改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>
.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; }
(香草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
当滚动条消失时,还应用a来避免基础文本上的重排。
.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;
}