我在容器中有一个固定的 block 元素。滚动时,固定定位的元素超出了容器。我知道固定元素将根据窗口 vw 定位。但是有什么方法可以确保固定定位的元素只会滚动到容器位置。固定位置元素不能超出容器
问题如下所示。
https://codepen.io/anon/pen/dKLByX
我尝试使用以下方法解决问题:
if($(window).scrollTop()>1900){
$('.fixed-ct').css({'bottom':'200px','top':'auto'});
}else if($(document).scrollTop() <=100) {
$('.fixed-ct').css({'top':'10px','bottom':'auto'});
}else {
$('.fixed-ct').css({'top':'0px','bottom':'auto'});
}
但有时由于底部 200px,固定容器在末尾,它应该在滚动时使用 top:0px 位于顶部,并且它应该在容器本身内。
最佳答案
好了,在 .fixed-ct 中使用 position sticky 并添加 position:relative 到 .main-ct
.main-ct {
width: 1000px;
height:600px;
border: 1px solid #000;
position:relative;
}
.fixed-ct {
position: sticky;
width:100px;
height:20px;
background: red;
top:10px;
}
.like-body {
width: 100%;
height:1300px;
}
<div class="like-body">
<div class="main-ct">
<div class="fixed-ct"></div>
</div>
</div>
关于jquery - 仅在 div 容器内固定位置元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51174427/