How can I retain the scroll position of a scrollable area when pressing back button?

后端 未结 5 1759
故里飘歌
故里飘歌 2020-12-01 03:15

I have a long list of links inside a big scrollable div. Each time when a user click on a link then click the back button, it starts at the very top of the div. It is not us

5条回答
  •  一个人的身影
    2020-12-01 03:50

    If a back button is kind of history back button window.history.back() Then what you are seeking for, is a default browser functionality. So you don't have to worry about it.

    If your back button actually point to some URL in your application via link or form, then you have to take care that manually.

    For solution you may use cookies to store your page scroll value. Each time user scroll on your page, do save scroll value for that page to cookie. Extra work is applied to manual cookie management.

    window.onScroll = function(){
        document.cookie="pageid=foo-"+window.scrollY+";";
    }
    

    This cookie value can be use to set scroll value of the page on page visit.

    window.scroll(0,cookievalue);
    

提交回复
热议问题