历史记录pushState和滚动位置 [英] history pushState and scroll position
问题描述
当用户使用HTML5 popstate处理程序在浏览器历史记录中导航时,我正在尝试检索滚动位置.
I am trying to retrieve the scroll position when a user navigates back in the browser history using HTML5 popstate handler.
这就是我所拥有的:
$(document).ready(function () {
$(window).on('popstate', PopStateHandler);
$('#link').click(function (e) {
var stateData = {
path: window.location.href,
scrollTop: $(window).scrollTop()
};
window.history.pushState(stateData, 'title', 'page2.html');
e.preventDefault();
});
});
function PopStateHandler(e) {
alert('pop state fired');
var stateData = e.originalEvent.state;
if (stateData) {
//Get values:
alert('path: ' + stateData.path);
alert('scrollTop: ' + stateData.scrollTop);
}
}
<a id="link" href="page2.html"></a>
当我向后浏览时,我无法检索stateData的值.
When I navigate back, I am unable to retrieve the values of the stateData.
我认为这是因为popstate检索的是初始页面加载的值,而不是单击超链接时我推送到历史记录的状态.
I presume this is because the popstate is retrieving the values of the initial page load and not the state I pushed to the history when the hyperlink was clicked.
我该如何返回导航位置?
How could I go about getting the scroll position on navigating back?
推荐答案
我自己解决了这个问题:
I managed to solve this one myself:
在导航到新页面之前,我们必须覆盖历史记录堆栈上的当前页面.
We must overwrite the current page on the history stack before navigating to the new page.
这使我们可以存储滚动位置,然后在向后导航时将其从堆栈中弹出:
This allows us to store the scroll position and then pop it off the stack when we navigate back:
$('#link').click(function (e) {
//overwrite current entry in history to store the scroll position:
stateData = {
path: window.location.href,
scrollTop: $(window).scrollTop()
};
window.history.replaceState(stateData, 'title', 'page2.html');
//load new page:
stateData = {
path: window.location.href,
scrollTop: 0
};
window.history.pushState(stateData, 'title', 'page2.html');
e.preventDefault();
});
这篇关于历史记录pushState和滚动位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!