我目前正在开发一个支持 ajax 的网站。浏览网站和浏览器历史记录效果很好,但有一个问题我无法解决。
当用户按下后退按钮时,最后一页会再次出现。但是,虽然我通过 popstate 事件将垂直滚动位置设置为上一个,但它又跳回顶部......
function loadContent(nextContent, nextUrl, newPage = true) {
var currUrl = window.location.pathname;
currUrl = currUrl.slice(7,currUrl.length);
var scrollY = window.scrollY;
var prevContent = document.getElementById("page").innerHTML;
document.getElementById("page").innerHTML = nextContent;
if (newPage) {
// overwrite current history entry
history.replaceState({ content: prevContent, url: currUrl, scrollY: scrollY }, null, currUrl);
initPage();
window.scrollTo(0,0);
// write new entry
history.pushState({ content: nextContent, url: nextUrl, scrollY: 0 }, null, nextUrl);
} else {
initPage();
// scroll to previous scroll position
window.scrollTo(0,history.state.scrollY);
}
}
window.onpopstate = function(e) {
loadContent(e.state.content, e.state.url, false);
// page scrollY will be set in load, after page content was added
}
我知道代码到目前为止是有效的,因为之前我在 window.scrollTo() 之后放置了一个警报,并且在卡住期间我看到页面位于正确的位置。但继续下去后,它跳到了顶部。是否可能存在另一个(默认)事件,在后台滚动到顶部?
感谢帮助
最佳答案
我现在通过将 onpopstate 函数更改为以下内容解决了该问题:
window.onpopstate = function(e) {
loadContent(e.state.content, e.state.url, false);
// as previous window.scrollTo() have no effect, do it within a few millisecs again
setTimeout(function() {
window.scrollTo(0,history.state.scrollY);
}, 5);
}
虽然不是很漂亮,但确实有效。如果有人知道一个干净的解决方案或发生这种效果的原因,请分享您的知识!
关于javascript - 防止Ajax网站按下后退按钮后跳回顶部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47072166/