简体   繁体   English

平滑滚动+粘性标题会导致高度变化吗?

[英]Smooth scroll + sticky header accounting for height change?

I have a navigation area that turns into a sticky header once you scroll past it and I also have a smooth scrolling function to scroll the page to specific sections when you click on different links. 我有一个导航区域,一旦你滚过它就变成一个粘性标题,我也有一个平滑的滚动功能,当你点击不同的链接时,页面滚动到特定的部分。 The problem I am having is that if you click one of the links before the navigation becomes sticky, the page scrolls too far past the section because the offset is using the initial height of the navigation rather than the sticky height. 我遇到的问题是,如果在导航变粘之前单击其中一个链接,页面会在该部分之间滚动太远,因为偏移是使用导航的初始高度而不是粘性高度。 The same thing happens in the opposite direction as well, if you click on the link to the first section, it scrolls too far up because it uses the height of the sticky nav as the offset. 同样的事情也发生在相反的方向,如果你点击第一部分的链接,它会向上滚动得太远,因为它使用粘性导航的高度作为偏移量。 Is there an easy way to solve for this? 有没有一种简单的方法来解决这个问题?

$(function() {
    // Smooth scrolling
    $('nav li').click(function() {
    var navHeight = $('nav').height();
    var section = $(this).attr('class');
    var target = $('#'+section);
    if (target.length) {
      $('html,body').animate({
        scrollTop: target.offset().top - navHeight
      }, 750);
      return false;
    }
  });

  // Sticky nav
  var navTop = $('nav').offset().top;
  var stickyNav = function() {
    var scrollTop = $(window).scrollTop();

    if (scrollTop > navTop) { 
      $('nav').addClass('sticky');
    } else {
      $('nav').removeClass('sticky'); 
    }
  };
  stickyNav();

  $(window).scroll(function() {
    stickyNav();
  });
});

JSFiddle example JSFiddle示例

You might be able to just add the 'sticky' class to the nav when the user clicks on an element. 当用户点击元素时,您可以将“粘性”类添加到导航中。

$(function() {
    // Smooth scrolling
    $('nav li').click(function() {
    var section = $(this).attr('class');
    var target = $('#'+section);
    if (target.length) {
      if (target.offset().top > navTop){
        $('nav').addClass('sticky');
      }
      var navHeight = $('nav').height();
      $('html,body').animate({
        scrollTop: target.offset().top - navHeight
      }, 750);
      return false;
    }
  });

  // Sticky nav
  var navTop = $('nav').offset().top;
  var stickyNav = function() {
    var scrollTop = $(window).scrollTop();

    if (scrollTop > navTop) { 
      $('nav').addClass('sticky');
    } else {
      $('nav').removeClass('sticky'); 
    }
  };
  stickyNav();

  $(window).scroll(function() {
    stickyNav();
  });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM