Demo: 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的整个可滚动区域的覆盖?
这是一个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、控制台、输出