出现粘性导航时页面跳转

Page jumps when sticky navigation appears

我正在尝试在您滚动到第一部分(关于全身治疗)后向页面添加粘性导航。

View webpage here

See code on GitHub here

但是,粘性导航一出现,页面就跳转了。当您单击导航栏中的 "Systemic Psychotherapy" 时,这也会影响页面的着陆位置。它没有落在该部分的顶部,而是覆盖了标题和前几句话。但是,这只会在您单击页面顶部时发生。

我试过使用 Waypoints:

$('.js--section-about-st').waypoint(function(direction) {
    if (direction == "down") {
        $('nav').addClass('sticky');
    } else {
        $('nav').removeClass('sticky');
    }
});

和jQuery:

$(window).scroll(function() {
  if ($(this).scrollTop() > 400){
    $('nav').addClass('sticky'); 
   }
  else{
    $('nav').removeClass('sticky');
  }

导航栏变粘时会缩小。我读到这会导致页面跳转,所以我试着保持它的大小不变,但它仍然跳转。

谁能帮我弄清楚我哪里出错了?

谢谢!

当您创建一个元素 position: fixed; 时,它会从页面流中移除,这意味着它不会影响其他元素。它曾经占据的任何高度都被取消了。 Here is an example of this behavior.

非粘性导航是105px,所以当它变得粘性时,导航之后的所有元素都会向上移动105px 占据那个space。考虑将与 padding-top 相同的 105px 应用到 <body> 以弥补现在缺少的导航栏。 Here is the same example from above, but with the fix now in place.

$(window).scroll(function() {
  if ($(this).scrollTop() > 400){
    $('nav').addClass('sticky'); 
    $('body').css('padding-top', '105px'); //Height of non-stick nav
   }
  else{
    $('nav').removeClass('sticky');
    $('body').css('padding-top', '');
  }
});