我正在尝试实现一个小代码,当我单击锚点时(并且锚点名称出现在动画之后),我可以使用它实现平滑滚动,并且如果我按下浏览器的后退按钮,我想返回到页面顶部并更新 URL(不带 #anchor 名称)。
这是代码:
$(function() {
// Smooth scrolling when clicking on anchor
$('a[href*=#]:not([href=#])').click(function(event) {
event.preventDefault();
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
if (target.length) {
var hash = this.hash;
$('html,body').animate({ scrollTop: target.offset().top - 55}, 300, function() {
location.hash = hash;
href = window.location.href;
history.pushState({page:href}, null, href);
});
return false;
}
}
});
// Get smooth scrolling to the top whith back button of browser
$(window).bind('popstate', function(event) {
var state = event.originalEvent.state;
var target = window.location.href.split('#');
var href = target[0];
if (state) {
$('html,body').animate({ scrollTop: 0 }, 300, function() {
window.location.href = href;
})
}
});
// First page loading
window.onload = function() {
history.replaceState({ path: window.location.href }, '');
}
});
以上所有功能在 Safari 和 Chrome 下都能正常运行。但 Firefox 的情况并非如此:一旦执行平滑向下滚动,我需要单击两次后退按钮才能重定向到页面顶部。
我见过stackoverflow 上的另一个问题 https://stackoverflow.com/questions/9634518/popstate-need-to-click-twice-on-back-button-to-actually-get-back并尝试使用和不使用 event.preventDefault 进行操作,也只放置:
$('html').animate
or $('body').animate
但行为是一样的。
如果有人能明白为什么它不起作用。
Thanks
您正在触发此行中的其他历史记录更改location.hash = hash;
所以,我对你的代码做了一些更改,现在它可以在我的 FF 中运行了。
在点击处理程序中,
$('html').animate({ scrollTop: target.offset().top - 55}, 300, function() {
href = window.location.href;
history.pushState({page:href}, null, href.split('#')[0]+hash);
});
另外,似乎$('html,body').animate
运行回调两次,因此会扰乱历史记录。这就是为什么我只留下html。
在 popstate 处理程序中,我删除了页面重新加载,但如果您愿意,您可以保留它:
if (state) {
$('html,body').animate({ scrollTop: 0 }, 300)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)