【问题标题】:Improve smooth scrolling in order to get anchor links on the URL Adress bar改进平滑滚动以获得 URL 地址栏上的锚链接
【发布时间】:2016-04-11 22:30:53
【问题描述】:

正如标题所说,我找到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

【问题讨论】:

    标签: javascript jquery scroll anchor smooth-scrolling


    【解决方案1】:

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

    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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-25
      • 2013-07-17
      • 2022-07-13
      相关资源
      最近更新 更多