历史pushState和滚动位置

时间:2013-05-24 09:05:05

标签: javascript jquery html5 pushstate html5-history

当用户使用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正在检索初始页面加载的值,而不是单击超链接时我推送到历史记录的状态。

我怎样才能在导航回来时获得滚动位置?

2 个答案:

答案 0 :(得分:22)

我自己设法解决了这个问题:

我们必须在导航到新页面之前覆盖历史堆栈上的当前页面。

这允许我们存储滚动位置,然后当我们向后导航时将其从堆栈中弹出:

    $('#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();

    });

答案 1 :(得分:1)

找到一种方法,使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类链接上的每次点击推送历史状态,以获取结果列表