我一直在寻找一个“灯箱”类型的解决方案,允许这一点,但还没有找到一个(请建议,如果你知道任何)。

我试图重现的行为就像你在Pinterest上点击图片时看到的一样。覆盖层是可滚动的(整个覆盖层向上移动,就像一页在一页的顶部),但覆盖层后面的主体是固定的。

我试图用CSS创建这个(即一个div覆盖在整个页面和身体溢出:隐藏),但它不阻止div是可滚动的。

如何保持主体/页面从滚动,但保持滚动在全屏容器内?


当前回答

所选的答案是正确的,但有一些局限性:

用你的手指进行超硬的“投掷”仍然会在后台滚动<body> 在模态中点击<input>打开虚拟键盘将引导所有未来滚动到<body>

我没有解决第一个问题,但想对第二个问题有所了解。令人困惑的是,Bootstrap曾经记录了键盘问题,但他们声称已经修复,并引用http://output.jsbin.com/cacido/quiet作为修复的例子。

事实上,这个例子在我的iOS测试中运行良好。但是,将其升级到最新的Bootstrap (v4)会破坏它。

为了弄清楚它们之间的区别,我减少了一个测试用例,使其不再依赖于Bootstrap, http://codepen.io/WestonThayer/pen/bgZxBG。

决定因素很奇怪。避免键盘问题似乎要求没有在包含模态的根目录<div>上设置background-color,并且模态的内容必须嵌套在另一个<div>中,可以设置background-color。

要测试它,在Codepen示例中取消注释下面的行:

.modal {
  position: fixed;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  z-index: 2;
  display: none;
  overflow: hidden;
  -webkit-overflow-scrolling: touch;
  /* UNCOMMENT TO BREAK */
/*   background-color: white; */
}

其他回答

当到达内容的顶部/底部时,CSS属性允许覆盖浏览器默认的溢出滚动行为。

只需添加以下样式叠加:

.overlay {
   overscroll-behavior: contain;
   ...
}

Codepen演示

目前工作在Chrome, Firefox和IE(caniuse)

欲了解更多详细信息,请查看谷歌开发人员文章。

大多数解决方案都存在无法保留滚动位置的问题,所以我研究了Facebook是如何做到这一点的。除了将底层内容设置为position: fixed之外,他们还动态设置顶部以保留滚动位置:

scrollPosition = window.pageYOffset;
mainEl.style.top = -scrollPosition + 'px';

然后,当你再次移除覆盖时,你需要重置滚动位置:

window.scrollTo(0, scrollPosition);

我创建了一个小示例来演示这个解决方案

let overlayShown = false; let scrollPosition = 0; document.querySelector('.toggle').addEventListener('click', function() { if (!overlayShown) { showOverlay(); } else { removeOverlay(); } overlayShown = !overlayShown; }); function showOverlay() { scrollPosition = window.pageYOffset; const mainEl = document.querySelector('.main-content'); mainEl.style.top = -scrollPosition + 'px'; document.body.classList.add('show-overlay'); } function removeOverlay() { document.body.classList.remove('show-overlay'); window.scrollTo(0, scrollPosition); const mainEl = document.querySelector('.main-content'); mainEl.style.top = 0; } .main-content { background-image: repeating-linear-gradient( lime, blue 103px); width: 100%; height: 200vh; } .show-overlay .main-content { position: fixed; left: 0; right: 0; overflow-y: scroll; /* render disabled scroll bar to keep the same width */ /* Suggestion to put: overflow-y: hidden; Disabled scrolling still makes a mess with its width. Hiding it does the trick. */ } .overlay { display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0, 0, 0, 0.3); overflow: auto; } .show-overlay .overlay { display: block; } .overlay-content { margin: 50px; background-image: repeating-linear-gradient( grey, grey 20px, black 20px, black 40px); height: 120vh; } .toggle { position: fixed; top: 5px; left: 15px; padding: 10px; background: red; } /* reset CSS */ body { margin: 0; } <main class="main-content"></main> <div class="overlay"> <div class="overlay-content"></div> </div> <button class="toggle">Overlay</button>

对于触摸设备,尝试在覆盖的包装中添加一个1px宽,101vh min-height的透明div。然后添加-webkit-overflow-scrolling:touch;overflow-y:汽车;对包装。这将使移动safari误以为覆盖层是可滚动的,从而拦截来自主体的触摸事件。

这是一个示例页面。在移动safari上打开:http://www.originalfunction.com/overlay.html

https://gist.github.com/YarGnawh/90e0647f21b5fa78d2f678909673507f

如果有人正在寻找React函数组件的解决方案,你可以把它放在模态组件中:

 useEffect(() => {
    document.body.style.overflowY = 'hidden';
    return () =>{
      document.body.style.overflowY = 'auto';
    }
  }, [])

理论

看看pinterest网站的当前实现(未来可能会改变),当你打开覆盖时,一个noscroll类被应用到body元素(设置溢出:隐藏),使body不再可滚动。

动态创建的覆盖或已经注入到页面中并通过display: block可见-这没有什么区别-具有position: fixed和overflow-y: scroll,顶部,左侧,右侧和底部属性设置为0:这种风格使覆盖填充整个视口(但现在我们是在2022年,所以你可以使用inset: 0代替)。

覆盖层内的div位于position: static,因此垂直滚动条与该元素相关。这将产生一个可滚动但固定的覆盖。

当你关闭覆盖时,你必须隐藏它(使用display: none),你甚至可以通过javascript删除节点(或者只是里面的内容,这取决于你,但也取决于内容的性质)。

最后一步是删除应用于主体的noscroll类(这样溢出属性就会回到它之前的值)


Code

Codepen例子

(它通过改变overlay的aria-hidden属性来显示和隐藏它,并增加其可访问性)。

标记 (打开按钮)

<button type="button" class="open-overlay">OPEN LAYER</button>

(覆盖和关闭按钮)

<section class="overlay" aria-hidden="true" tabindex="-1">
  <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;
   inset: 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"]'),
    openingBtt;
    
[].forEach.call(overlayBtts, function(btt) {

  btt.addEventListener('click', function() { 
     
     /* Detect the button class name */
     var overlayOpen = this.className === 'open-overlay';
     
     /* storing a reference to the opening button */
     if (overlayOpen) {
        openingBtt = this;
     }
     
     /* 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;
     
      /* forcing focus for Assistive technologies but note:
    - if your modal has just a phrase and a button move the
      focus on the button
    - if your modal has a long text inside (e.g. a privacy
      policy) move the focus on the first heading inside 
      the modal
    - otherwise just focus the modal.

    When you close the overlay restore the focus on the 
    button that opened the modal.
    */
    if (overlayOpen) {
       overlay.focus();
    }
    else {
       openingBtt.focus();
       openingBtt = null;
    }

  }, false);

});

/* detect Escape key when the overlay is open */
document.body.addEventListener('keyup', (ev) => {
   if (ev.key === "Escape" && overlay.getAttribute('aria-hidden') === 'false') {
      overlay.setAttribute('aria-hidden', 'true');
      body.classList.toggle('noscroll', false);
      openingBtt.focus();
      openingBtt = null;
   }
})

最后,这是另一个例子,在这个例子中,覆盖通过应用于不透明属性的CSS转换以淡入效果打开。此外,还应用右填充来避免滚动条消失时底层文本的回流。

代码示例(淡出)

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;
     inset: 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; 
}