最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to add offset to jquery scrolltop - Stack Overflow

programmeradmin1浏览0评论

I am using the following code to animate scroll from a menu link in a navbar on 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
});

At the moment, the fixed navbar hides the anchor underneath. How can I add an offset of 60px to adjust for this?

I am using the following code to animate scroll from a menu link in a navbar on 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
});

At the moment, the fixed navbar hides the anchor underneath. How can I add an offset of 60px to adjust for this?

Share Improve this question asked Aug 17, 2013 at 13:06 alias51alias51 8,64822 gold badges106 silver badges185 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 8

You need to subtract 60 from the offset().top of the target element, to allow space for the navbar. I've done this dynamically by getting the height() of the #subnavbar so that should you ever need to change it's height in ther future, you don't need to worry about breaking this code.

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

评论列表(0)

  1. 暂无评论