gpt4 book ai didi

javascript - jQuery 平滑滚动不会更改 URL

转载 作者:行者123 更新时间:2023-11-29 15:42:35 24 4
gpt4 key购买 nike

一切正常,但是当 jQuery 就位时,URL 不会改变。无论如何让它平滑滚动并同时更改网址?在此之前我尝试了一种不同的方法,但是它不像这个那样跨浏览器兼容。

我的 HTML 是:

<li class="representing-you-online"><a href="#representing-you-online">Representing you online</a></li>
<li class="developing-your-people"><a href="#developing-your-people">Developing your people</a></li>

我的 jQuery 是:

$(document).ready(function() {
$('a[href^="#"]').click(function() {
var target = $(this.hash);
if (target.length == 0) target = $('a[name="' + this.hash.substr(1) + '"]');
if (target.length == 0) target = $('html');
$('html, body').animate({ scrollTop: target.offset().top }, 500);
return false;
});
});
$(document).ready(function(){
$('#logo a').click(function () {
$('body,html').animate({
scrollTop: 0
}, 800);
return false;
});
});

谢谢!

最佳答案

像这样替换 anchor 的点击处理代码:

$(document).ready(function() {
$('a[href^="#"]').click(function() {
var target = $(this.hash);
var hash = this.hash;
if (target.length == 0) target = $('a[name="' + this.hash.substr(1) + '"]');
if (target.length == 0) target = $('html');
$('html, body').animate({ scrollTop: target.offset().top }, 500, function (){
location.hash = hash;
});
return false;
});
});

请注意 jquery .animate() 末尾的完整函数。它会更改 URL。

查看演示 here .

关于javascript - jQuery 平滑滚动不会更改 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16889215/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com