history pushState and scroll position

大城市里の小女人 提交于 2019-12-05 12:00:30

问题


I am trying to retrieve the scroll position when a user navigates back in the browser history using HTML5 popstate handler.

Here is what I have:

$(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>

When I navigate back, I am unable to retrieve the values of the stateData.

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?


回答1:


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();

    });



回答2:


Find a way to make this more dynamic with jQuery, hope this can help :

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

here the solution without 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);
}

This will push history state for each click on link with lienDetail class for list of results for example



来源:https://stackoverflow.com/questions/16731271/history-pushstate-and-scroll-position

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!