简体   繁体   中英

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

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();
  });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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