历史推送状态和滚动位置

history pushState and scroll position

本文关键字:滚动 位置 状态 历史      更新时间:2023-09-26

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

想办法用jQuery让它更有动态性,希望能有所帮助:

$(".lienDetail a").on('click',function(){
    history.pushState({scrollTop:document.body.scrollTop},document.title,document.location.pathname);
}

这里没有jQuery的解决方案:

function pushHistory(e){
    e = e || window.event;
    var target;
    target = e.target || e.srcElement;
    if (target.className.match(/'blienDetail'b/)){
        history.pushState({scrollTop:document.body.scrollTop},document.title,document.location.pathname);
    }
}
if (document.body.addEventListener)
{
        document.body.addEventListener('click',pushHistory,false);
}
else
{
    document.body.attachEvent('onclick',pushHistory);
}

这将为每次点击链接推送历史状态与lienDetail类的结果列表,例如