jquery - 如何在页脚处停止固定位置滚动

标签 jquery html css

我对此做了很多研究,但我似乎无法弄清楚为什么这对我不起作用。

我有两个 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,并使用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
});

这是一个 fiddle :https://jsfiddle.net/xpvt214o/93144/

关于jquery - 如何在页脚处停止固定位置滚动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49763846/

相关文章:

javascript - BootstrapValidator - 禁用给定字段的特定验证

javascript - 将鼠标悬停在日期时间输入字段上时禁用滚动

javascript - 如何使用 Javascript 或 jQuery 获取背景颜色?

javascript - AngularJS:将父级 <div> 每 n 个元素分开

javascript - 将 Enter 作为新行从 textarea 标签转换为 div 标签

html - 根据屏幕大小有条件地显示 RenderBody

html - 段落在 Firefox 中重叠

css - 如何根据查询字符串参数更改 CSS 类

css - 在几何形状 div 中对齐文本

javascript - 对话框和自动高度