改进平滑滚动,以便在URL地址栏上获取锚点链接

时间:2016-01-07 13:47:01

标签: javascript jquery scroll anchor smooth-scrolling

正如标题所说,我找到this script以获得平滑滚动并稍微改进一下,现在它看起来像这样:

  $('a[href*=#]:not([href=#])').on('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 - 50 // in this case 50px BEFORE
        }, 1000);
        return false;
      }
    }
  });

当用户点击锚链接时触发。

问题是URL地址没有变化。我还想更改用户URL地址栏,以便每次用户点击使其滚动的链接时显示锚链接。

提前感谢你能给我的任何帮助。

PS:您可以看到我正在测试此here的网站。

1 个答案:

答案 0 :(得分:0)

您可以使用以下方式更改地址:

if (target.length) {
    history.replaceState(null, null, this.hash);
    $('html,body').animate({
        scrollTop: target.offset().top - 50 // in this case 50px BEFORE
    }, 1000);
    return false;
}

如果您要更新浏览器历史记录,请改为使用:

history.pushState(null, null, this.hash);

More info