滚动到锚点上方100像素

Scroll to 100px above the anchor

本文关键字:100像素 滚动      更新时间:2023-09-26

我正在使用下面的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;
  });
});

感谢

从target.offset().top中减去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;
  });
});