使内容在滚动到jQuery中的某个点时保持粘性

问题描述 投票:3回答:2

我有一个div设置为position: relative。窗口顶部到达时,它变为fixed。 div位于一个容器中(在下面的示例中为蓝色),当它到达其父容器的底部(蓝色)时,我想将其设置回relative

这是我的代码简化而我的Fiddle

HTML:

<div class="green"></div>

<div class="blue">
  <div class="sticky">Sticky</div>
</div>

<div class="red"></div>

CSS:

.blue {
  background-color: blue;
  height: 500px;
}

.sticky {
  width: 200px;
  background-color: yellow;
  text-align: center;
  top: 0;
}

.red {
  background-color: red;
  height: 800px;
}

.green {
  background-color: green;
  height: 200px;
}

和jQuery:

$(document).ready(function() {
  var stickyTop = $('.sticky').offset().top;

  $(window).scroll(function() {
    var windowTop = $(window).scrollTop();

    if (stickyTop < windowTop) {
      $('.sticky').css('position', 'fixed');
    } else {
      $('.sticky').css('position', 'relative');
    }
  });
});
jquery scroll fixed sticky
2个回答
5
投票

if语句中添加以下条件:

$(".blue").height() + $(".blue").offset().top > windowTop

您的代码应如下所示:

$(document).ready(function() {
  var stickyTop = $('.sticky').offset().top;

  $(window).scroll(function() {
    var windowTop = $(window).scrollTop();
    if (stickyTop < windowTop && $(".blue").height() + $(".blue").offset().top - $(".sticky").height() > windowTop) {
      $('.sticky').css('position', 'fixed');
    } else {
      $('.sticky').css('position', 'relative');
    }
  });
});

请参见updated JSFiddle


0
投票

这里是解决方法:

$(window).scroll(function() {
       var navpos1 = $('.header').offset().top(); 
           if (navpos1) {
              $('body').addClass('fixedHd');
            } else {
                 $('body').removeClass('fixedHd');
                 }
  });  
© www.soinside.com 2019 - 2024. All rights reserved.