簡體   English   中英

使用平滑滾動功能時如何考慮導航欄的高度

[英]How to account for the height of a navbar when using a smooth scroll 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;
  }
}
  });
});

您需要將導航欄的高度添加到scrollTop: target.offset().top 這是一個整數值,可以通過簡單地引用導航欄DOM元素本身的.height()來計算。

這是一個示例,假設導航欄的類別為navbar

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

希望這可以幫助! :)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM