滚动到锚点上方100px

Wis*_*guy 6 javascript scroll target

我正在使用下面的JavaScript代码创建从导航到锚点的滚动效果.

我遇到的问题是我希望滚动停止在锚点上方100px.

我需要在此代码中更改哪些内容才能实现此结果?

$(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;
  });
});
Run Code Online (Sandbox Code Playgroud)

谢谢

Dam*_*aux 14

从target.offset().顶部减去100个像素.像这样:

$(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;
  });
});
Run Code Online (Sandbox Code Playgroud)