我试图实现一个小代码,当我点击锚(锚名称出现在动画后)时,我可以顺利滚动,如果我按下浏览器的后退按钮并更新URL (没有#锚名),我想返回到页面的顶部。
下面是代码:
$(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的情况并非如此:一旦顺利地向下滚动,我需要在页面顶部单击“后退”按钮两次才能被重定向。
我见过this other question on stackoverflow,并且尝试使用和不使用event.preventDefault,并且只使用:
$('html').animate
或$('body').animate
但行为是一样的。
如果有人能明白为什么它不起作用。
谢谢
发布于 2016-02-06 22:28:11
您正在触发这行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)
https://stackoverflow.com/questions/35086895
复制相似问题