gpt4 book ai didi

javascript - 历史 pushState 和滚动位置

转载 作者:技术小花猫 更新时间:2023-10-29 12:19:08 25 4
gpt4 key购买 nike

当用户使用 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();

});

关于javascript - 历史 pushState 和滚动位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16731271/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com