【问题标题】:Make content sticky on scroll to a point in jQuery使内容在滚动到jQuery中的某个点时保持粘性
【发布时间】:2022-02-22 16:22:50
【问题描述】:

我有一个设置为position: relativediv。当窗口顶部到达它时,它变为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


    【解决方案1】:

    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

    【讨论】:

      【解决方案2】:

      你可以用jquery.sticky.js插件来实现

      为要粘贴的元素添加一个id

      $('#sticky').sticky();
      

      【讨论】:

        【解决方案3】:

        这里有一个解决方案:

        $(window).scroll(function() {
               var navpos1 = $('.header').offset().top(); 
                   if (navpos1) {
                      $('body').addClass('fixedHd');
                    } else {
                         $('body').removeClass('fixedHd');
                         }
          });  
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-07-19
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-10-17
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多