【问题标题】:Scroll to 100px above the anchor滚动到锚点上方 100px
【发布时间】:2013-08-16 13:23:45
【问题描述】:

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

我遇到的问题是我希望滚动在锚点上方 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 }, 1000);
      return false;
  });
});

谢谢

【问题讨论】:

    标签: javascript scroll target


    【解决方案1】:

    从 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;
      });
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-11-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-14
      • 2021-08-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多