返回时OnScroll粘滞标题

OnScroll Sticky header while getting back

本文关键字:标题 OnScroll 返回      更新时间:2023-09-26

我创建了这个Fiddle:https://jsfiddle.net/empafmw8/

我的一切都很好,但当你滚动回网站顶部时,当你滚动到0时,.sticky-header会将其position更改为relative。但我需要这样做,当.first出现在屏幕上时。

如果.firstheight: 100% ,我也需要它来工作

我试过else if ($(window).scrollTop() == 800px)else if ($(window).scrollTop() == 100%)之类的东西,但不起作用。

试试这个(请参阅我的更改注释):

$(document).ready(function() {
  var firstHeight = $('.first').outerHeight(); // get the height of the /first div
  //header
  $(window).scroll(function() {
    if ($(window).scrollTop() > $('.sticky-header').offset().top && !$('.sticky-header').hasClass('posi')) {
      $('.sticky-header').addClass('posi');
    } else if ($(window).scrollTop() <= firstHeight && $('.sticky-header').hasClass('posi')) { // remove the class if the height is less than or equal to the height of the first div
      $('.sticky-header').removeClass('posi');
    }
  });
});
.first {
  width: 100%;
  height: 800px;
  background: red;
}
.second {
  width: 100%;
  height: 2000px;
  background: blue;
}
.sticky-header {
  width: 100%;
  height: 80px;
  background-color: green;
}
.posi {
  margin-top: 0;
  top: 0;
  position: fixed;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="first"></div>
<div class="second">
  <div class="sticky-header"></div>
</div>

或者,您可以使用原始偏移顶部执行if-else操作-只需将hasClass移动到其中:更新后的fiddle,它的效率更高

您可以尝试else if ($(window).scrollTop() < $('.second').offset().top)-一旦.first出现在屏幕上,这将使粘性标头返回到原来的位置。

小提琴示例。