【问题标题】:URL not updating in address bar after clicking anchor link单击锚链接后,地址栏中的 URL 未更新
【发布时间】:2018-12-04 03:49:48
【问题描述】:

我正在使用一个小 jQuery 来平滑滚动到锚定链接。这很有效,但单击链接不会更新地址栏中的 URL。我希望更新 URL 以包含点击链接的新哈希。

我在这里发现了类似的问题,但他们的原始代码与我的完全不同,以至于我无法弄清楚如何将其实现到我的中。

$('a[href^="#"]').click(function () {
    $('html, body').animate({
        scrollTop: $('[name="' + $.attr(this, 'href').substr(1) + '"]').offset().top
    }, 800);

    return false;
});
<html>
<body>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<style>
p {
margin-bottom: 200px;
}
</style>
</head>
<a href="#anchor1">Link to Anchor 1</a>
<a href="#anchor2">Link to Anchor 2</a>
<a href="#anchor3">Link to Anchor 3</a>
<a href="#anchor4">Link to Anchor 4</a>
<a name="anchor1"></a>
<p>Anchor 1</p>

<a name="anchor2"></a>
<p>Anchor 2</p>

<a name="anchor3"></a>
<p>Anchor 3</p>

<a name="anchor4"></a>
<p>Anchor 4</p>
</body>
</html>

【问题讨论】:

    标签: javascript jquery html


    【解决方案1】:

    由于您的点击处理程序中有return false,因此链接的默认行为被覆盖。这就是地址栏不更新 URL 的原因。

    您可以手动编辑 URL 的哈希部分:

    $('a[href^="#"]').click(function () {
        $('html, body').animate({
            scrollTop: $('[name="' + $.attr(this, 'href').substr(1) + '"]').offset().top
        }, 800);
    
        // update the URL in location bar
        window.location.hash = $.attr(this, 'href').substr(1);
    
        return false;
    });
    

    【讨论】:

      猜你喜欢
      • 2014-11-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-11
      • 1970-01-01
      • 2016-04-29
      相关资源
      最近更新 更多