history pushState and scroll position

后端 未结 2 716
無奈伤痛
無奈伤痛 2021-02-19 04:44

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:

$(docume         


        
2条回答
  •  南方客
    南方客 (楼主)
    2021-02-19 05:39

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

提交回复
热议问题