如何向jquery滚动条添加偏移量

How to add offset to jquery scrolltop

本文关键字:添加 偏移量 滚动条 jquery      更新时间:2023-09-26

我正在使用以下代码从引导程序上的导航栏中的菜单链接动画滚动:

$("#subnavbar ul li a[href^='#']").on('click', function(e) {
   e.preventDefault();
   $('html, body').animate({ scrollTop: $(this.hash).offset().top }, 600);
   // edit: Opera and IE requires the "html" elm. animated
});

此时,固定的导航栏将锚隐藏在下面。如何添加60px的偏移量来进行调整?

您需要从目标元素的offset().top中减去60,以便为导航栏留出空间。我已经通过获取#subnavbarheight()动态地完成了这一操作,这样,如果将来需要更改它的高度,就不必担心会破坏此代码。

$("#subnavbar ul li a[href^='#']").on('click', function(e) {
    e.preventDefault();
    $('html, body').animate({ 
        scrollTop: $(this.hash).offset().top - $('#subnavbar').height()
    }, 600);
});