我目前正在使用我发现的这段代码来自动滚动到 anchor :
$(function() {
$('nav a[href*=#]').bind('click',function(event){
var $anchor = $(this);
$('html, body').stop().animate({
scrollTop: $($anchor.attr('href')).offset().top - 100
}, 1000);
event.preventDefault();
});
});
我可以添加什么来确保单击时将 #anchor 添加到 URL?
我见过这个使用过,但我不知道如何添加它..
function() {
if(history.pushState) {
history.pushState(null, null, target);
}
else {
location.hash = target;
}
});
非常感谢!!!
最佳答案
运行它 when the animation is done :(nice demo here)
$(function () {
$('nav a[href*=#]').on('click', function (event) {
var $anchor = $(this),
name = $anchor.attr("href").match(/#(.+)/i)[1];
$('html, body').stop().animate({
scrollTop: $($anchor.attr('href')).offset().top - 100
}, 1000, function () {
if (history.pushState) {
history.pushState(null, null, "#" + name);
} else {
location.hash = name;
}
});
event.preventDefault();
});
});
关于javascript - 更改自动滚动的 URL(pushstate?),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11060186/