简体   繁体   中英

How to account for the height of a navbar when using a smooth scroll function

I have a smooth scroll function that is used to scroll to specific sections of my page when links are clicked on. However, when it automatically scrolls to a section, it does not account for the height of my fixed navbar, which ends up covering up some of the content. I would like to calculate the height of the navbar and subtract it from the scroll position within my current function

$(function() {
  $('a[href*="#"]:not(.carousel-control)').click(function() {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
  var target = $(this.hash);
  target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
  if (target.length) {
    $('html, body').animate({
      scrollTop: target.offset().top
  }, 1000);
    return false;
  }
}
  });
});

You need to add the height of your navbar to scrollTop: target.offset().top . This is an integer value, and can be calculated by simply referencing the .height() of the navbar DOM element itself.

Here's an example assuming a navbar with the class of navbar :

scrollTop: target.offset().top + $('.navbar').height()

Hope this helps! :)

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