我对此做了很多研究,但我似乎无法弄清楚为什么这对我不起作用。
我有两个 div 元素。其中一个 div 具有 position: fixed
以使其始终保持在窗口中。
一旦 div 到达页脚,它应该移除固定滚动并粘在页脚的顶部。我尝试使用在 this example 中找到的代码, 但当 div 到达页脚时,它只是弹回页面顶部。
这是一个 fiddle 的例子:
$(document).scroll(function (){
if($('.userInfo').offset().top + $('.userInfo').height() >= $('footer').offset().top - 10){
$('.userInfo').css('position', 'absolute');
}
if($(document).scrollTop() + window.innerHeight < $('footer').offset().top){
$('.userInfo').css('position', 'fixed');
}
});
.profileMain{
display: flex;
}
.userInfoContainer{
height: 100%;
width: 50%;
display: inline-block;
}
.userInfo{
background: red;
width: 50%;
position: fixed;
}
.userContent{
background: blue;
width: 50%;
margin-bottom: 10em;
}
footer{
background: gray;
width: 100%;
height: 30em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class = "profileMain">
<div class = "userInfoContainer">
<div class = "userInfo">f</div>
</div>
<div class = "userContent">f</div>
</div>
<footer></footer>
有人可以向我解释我在这里做错了什么吗?
最佳答案
要执行与您提供的示例相反的操作(将 div 粘贴到顶部而不是底部),从第二个 if
中删除 window.innerHeight
并进行比较滚动+元素的高度与页脚的offset
,并使用top
和bottom
定位将div放置在您想要的位置,
这应该可以解决问题:
$(document).scroll(function() {
if ($('.userInfo').offset().top + $('.userInfo').height() >= $('footer').offset().top - 10)
$('.userInfo').css({
'position': 'absolute',
'bottom': 0,
'top': 'auto'
});
if ($(document).scrollTop() + $('.userInfo').height() < $('footer').offset().top)
$('.userInfo').css({
'position': 'fixed',
'top': 0,
'bottom': 'auto'
}); // restore when you scroll up
});
这是一个 fiddle :https://jsfiddle.net/xpvt214o/93144/
关于jquery - 如何在页脚处停止固定位置滚动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49763846/