【问题标题】:Overlay doesn't cover overflow:scroll; Modal isn't fixed覆盖不包括溢出:滚动;模态不固定
【发布时间】:2017-01-04 08:57:20
【问题描述】:

演示:http://jsbin.com/zijisaxoke/1/edit?html,css,output

我有一个可滚动的容器,里面有一个内容 div(假设内容 div 的宽度可变)。但是,容器具有 100% 的固定宽度(也可以更改)。

我还有一个模态框,它有一个绝对定位的灰色叠加层。我的目标是让灰色覆盖覆盖容器的整个可滚动内容,但现在它只覆盖初始视口大小。我还想让模态本身固定在容器的左上角,无论滚动位置如何,但似乎position: fixed 不尊重父级的position: relative

.container {
  position: relative;
  width: 100%;
  height: 200px;
  background-color: red;
  overflow: scroll;
}
.content {
  width: 2000px;
  height: 300px;
}
.overlay {
  z-index: 200;
  position: absolute;
  opacity: 0.7;
  top: 0;
   left: 0;
   right: 0;
   bottom: 0;
   background-color: #000;
}
.modal {
  z-index: 500;
  position: fixed;
  width: 300px;
  background-color: green;
  top: 0;
  left: 0;
}
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
  <div class="stuff">hi</div>
  <div class="container">
    <div class="content">aaa</div>
    <div class="overlay"></div>
    <div class="modal">Hello</div>
  </div>
</body>
</html>

如何保持模态相对固定在容器内部,并保持覆盖覆盖 div 的整个可滚动区域?

【问题讨论】:

  • 固定位置总是从窗口计算它的位置并忽略相对位置。如果你想要这种行为,你需要使用绝对位置并在滚动事件上使用 JavaScript 操作覆盖位置。
  • @SimonJentsch 很高兴知道。但是,如果一切都与可滚动视口相关,我将如何操作覆盖位置?
  • 您需要在 JavaScript 中的可滚动.container 类上添加滚动事件。然后,每次触发此事件时,将覆盖层的顶部设置为容器的 scrollTop 属性。我稍后会添加答案。

标签: css


【解决方案1】:

这里是一个JS解决方案:

$('.container').on('scroll', function() {
  var scrollTop = $(this).scrollTop();
  $('.overlay').css('top', scrollTop);
  $('.overlay').css('bottom', -scrollTop);
});

和对应的JS Bin: http://jsbin.com/xahehodeqe/3/edit?html,css,js,console,output

【讨论】:

猜你喜欢
  • 2018-11-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-25
  • 2014-09-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多