当用户使用 HTML5 popstate 处理程序导航回浏览器历史记录时,我尝试检索滚动位置。
这是我所拥有的:
$(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 的值。
我认为这是因为 popstate 正在检索初始页面加载的值,而不是单击超链接时推送到历史记录的状态。
我怎样才能获得向后导航时的滚动位置?
我自己设法解决了这个问题:
在导航到新页面之前,我们必须覆盖历史堆栈上的当前页面。
这允许我们存储滚动位置,然后在返回时将其从堆栈中弹出:
$('#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();
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)