【发布时间】:2023-03-28 22:26:01
【问题描述】:
我对此进行了大量研究,但我似乎无法弄清楚为什么这对我不起作用。
我有两个 div 元素。其中一个 div 具有 position: fixed 以始终将其保留在窗口中。
一旦 div 碰到页脚,它应该移除固定滚动并粘在页脚的顶部。我已经尝试使用this example 中的代码,但是当 div 到达页脚时,它只会重新回到页面顶部。
这是一个小提琴的例子:
$(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>
有人可以向我解释我在这里做错了什么吗?
【问题讨论】:
-
当您切换到 position:fixed 时,我看不到您设置的最高位置。它将默认位于页面顶部。要修复,请在您的页脚 css 中,将顶部和左侧位置设置为您需要的位置。
-
@Korgrue 我不确定你的意思。这不是 jQuery 代码的问题吗?我尝试在
bottom: 0碰到页脚时设置它,但这也没有做任何事情。