如何在jQuery的scrollTop中添加偏移量

3
我将翻译如下内容:

我正在使用以下代码,在Bootstrap的导航栏中通过菜单链接实现滚动动画:

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

目前,固定的导航栏会遮挡住下面的锚点。我该如何添加60像素的偏移量来调整它呢?

1个回答

8

如果要为导航栏留出空间,您需要从目标元素的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);
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接