admin管理员组

文章数量:1405874

I'm using a little jQuery for a smooth scroll to anchored links. That much works, but clicking the links does not update the URL in the address bar. I want the URL to update to include the new hash of the clicked link.

I found similar questions on here, but their original code was different enough from mine that I couldn't figure out how to implement it into mine.

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

    return false;
});
<html>
<body>
<head>
<script src=".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>

I'm using a little jQuery for a smooth scroll to anchored links. That much works, but clicking the links does not update the URL in the address bar. I want the URL to update to include the new hash of the clicked link.

I found similar questions on here, but their original code was different enough from mine that I couldn't figure out how to implement it into mine.

$('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./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>

Share asked Dec 3, 2018 at 19:44 RobbyRobby 8333 gold badges27 silver badges62 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 7

Since you have return false in your click handler, the default behavior of the link is overriden. That's why the location bar doesn't update the URL.

You can manually edit the hash part of the 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;
});

本文标签: javascriptURL not updating in address bar after clicking anchor linkStack Overflow