您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

防止正文滚动,但允许覆盖滚动

防止正文滚动,但允许覆盖滚动

查看pinterest网站的当前实现(将来可能会更改),当您打开叠加层时,会将一个noscroll类应用于该body元素并overflow:hidden进行设置,因此该类body不再可滚动。

叠加(上即时或已经在页面内,并通过可见创建display: block,它使没有区别)有position : fixedoverflow-y: scroll,与topleftrightbottom属性设置为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; 
}
其他 2022/1/1 18:15:38 有252人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶