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

javascript - Scroll to 100px above the anchor - Stack Overflow

programmeradmin10浏览0评论

I'm using the the JavaScript code below to create a scroll effect from my nav to the anchor.

The problem I am having is I want the scrolling to stop 100px above the anchor.

What would I need to change in this code to achieve this result?

$(document).ready(function() {
  $('a[href^="#"]').click(function() {
      var target = $(this.hash);
      if (target.length == 0) target = $('a[name="' + this.hash.substr(1) + '"]');
      if (target.length == 0) target = $('html');
      $('html, body').animate({ scrollTop: target.offset().top }, 1000);
      return false;
  });
});

Thank you

I'm using the the JavaScript code below to create a scroll effect from my nav to the anchor.

The problem I am having is I want the scrolling to stop 100px above the anchor.

What would I need to change in this code to achieve this result?

$(document).ready(function() {
  $('a[href^="#"]').click(function() {
      var target = $(this.hash);
      if (target.length == 0) target = $('a[name="' + this.hash.substr(1) + '"]');
      if (target.length == 0) target = $('html');
      $('html, body').animate({ scrollTop: target.offset().top }, 1000);
      return false;
  });
});

Thank you

Share Improve this question asked Aug 16, 2013 at 13:23 WiseguyWiseguy 1552 gold badges2 silver badges9 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 16

Subtract 100 pixels from target.offset().top. like so:

$(document).ready(function() {
  $('a[href^="#"]').click(function() {
      var target = $(this.hash);
      if (target.length == 0) target = $('a[name="' + this.hash.substr(1) + '"]');
      if (target.length == 0) target = $('html');
      $('html, body').animate({ scrollTop: target.offset().top-100 }, 1000);
      return false;
  });
});
发布评论

评论列表(0)

  1. 暂无评论