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
1 Answer
Reset to default 7Since 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
版权声明:本文标题:javascript - URL not updating in address bar after clicking anchor link - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744947414a2633869.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论