【问题标题】:Link to Anchor on the same page minus some pixels链接到同一页面上的锚点减去一些像素
【发布时间】:2016-10-26 17:44:52
【问题描述】:

我将平滑滚动集成到页面的锚点。它适用于代码:

$(function() {
      $('a[href*="#"]:not([href="#"])').click(function() {
        if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
          var target = $(this.hash);
          target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
          if (target.length) {
            $('html, body').animate({
              scrollTop: target.offset().top
            }, 1000);
            return false;
          }
        }
      });
    });

现在,当我单击链接时,它会滚动到该位置。但由于我在顶部有一个固定的菜单栏(高度:100px),它与内容有点重叠。 我能以某种方式解决这个问题吗?就像在代码中说的:滚动到那个锚点减去 100px ...... 我认为它可能适用于

scrollTop: target.offset(-100).top

对吗?

【问题讨论】:

  • scrollTop: target.offset().top - 100 ?
  • 哦,谢谢!我试过了,但忘记了 - 和 100 之间的空格......愚蠢的我>。
  • 不客气。我在这里做了一个答案。也许将其标记为解决方案。 ;)

标签: javascript jquery html css


【解决方案1】:

jQuery 的offset 是一个只为您提供元素偏移量的函数。这并不意味着改变偏移量本身。之后减去 100px。

scrollTop: target.offset().top - 100

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-03-29
    • 1970-01-01
    • 2013-07-06
    • 1970-01-01
    • 2018-11-06
    • 1970-01-01
    • 2016-09-08
    相关资源
    最近更新 更多