【问题标题】:How to stop fixed position scrolling at footer如何在页脚处停止固定位置滚动
【发布时间】: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 碰到页脚时设置它,但这也没有做任何事情。

标签: jquery html css


【解决方案1】:

要与您提供的示例相反(将 div 粘贴到顶部而不是底部),从第二个 if 中删除 window.innerHeight 并将滚动+元素的高度与 offset 的页脚,并使用topbottom 定位将 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
});

这是一个小提琴:https://jsfiddle.net/xpvt214o/93144/

【讨论】:

  • 我很抱歉,我错过了我的问题的一个关键点。一旦 div 碰到页脚,我想删除固定位置并将其粘在页脚的顶部。我已编辑问题以包含此内容。
  • 喜欢这个jsfiddle.net/xpvt214o/93144 ?如果是我会更新答案
  • 是的,这就是我要找的。谢谢你。更新后将选择为正确答案
  • 你明白了,兄弟;)
  • 但是这些是这段代码的问题,你需要在第二个之后执行第一个if条件,互相交换
猜你喜欢
  • 2014-06-27
  • 2011-08-19
  • 2011-08-31
  • 2020-10-16
  • 1970-01-01
  • 2018-10-16
  • 1970-01-01
  • 1970-01-01
  • 2020-01-19
相关资源
最近更新 更多