禁用页面滚动但不隐藏滚动条

4
当我点击缩略图时,它会在顶部打开一个覆盖层div盒子:
.view-overlay {
  display:none;
  position:fixed;
  top:0;
  left:0;
  right:0;
  bottom:0;
  overflow-y:scroll;
  background-color:rgba(0,0,0,0.7);
  z-index:999;
}

对于没有浮动滚动条的浏览器,使用overflow: hidden禁用滚动会移除滚动条,导致内容向右移动一些以弥补额外的空间。我想保留滚动条来避免这种情况发生。网上有很多解决方案,但我找不到一个在所有浏览器中都能确定有效的解决方案。 https://dev59.com/P2oy5IYBdhLWcg3wN7YX#13891717- 这个答案似乎在Chrome上运行良好,但在Safari OSX 10.10上会出现奇怪的错误行为。 https://dev59.com/P2oy5IYBdhLWcg3wN7YX#8701977- 这个答案会导致页面回滚到顶部(Chrome)。
一个解决方案应该:
a) 打开遮罩时禁用正文滚动;
b) 使正文停留在原始滚动位置;
c) 保留滚动条,以避免内容偏移;
d) 在大多数/所有浏览器上工作,不会出现任何错误行为?
例如:https://dribbble.com就是这样做的,它在我测试过的浏览器上(包括Safari)似乎可以正常工作,没有出现任何错误行为。
1个回答

3

一种既简单又有效的方法是不将主要内容放在正文中,而是将其放在与覆盖层同级的包装器中。采用这种方法,您可以在不影响内容元素的滚动的情况下随时切换覆盖层。

var e = document.getElementById('overlay');
document.body.onclick = function() {
  e.style.display = (!e.style.display || e.style.display === 'block') ? 'none' : 'block';
};
html,
body,
#content {
  height: 100%;
  margin: 0;
}
#content {
  overflow: auto;
}
#high {
  height: 800px;
}
#overlay {
  position: absolute;
  height: 100%;
  width: 100%;
  background: rgba(0, 0, 0, 0.5);
}
<div id="overlay"></div>
<div id="content">
  Long content resides in this container
  <div id="high"></div>
  And the long content ends here
</div>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接