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

后端 未结 5 1758
故里飘歌
故里飘歌 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:43

    I think we should save scroll data per page, also we should use session storage instead of local storage since session storge effects only the current tab while local storage shared between all tabs and windows of the same origin

    $(function () {
                var pathName = document.location.pathname;
                window.onbeforeunload = function () {
                    var scrollPosition = $(document).scrollTop();
                    sessionStorage.setItem("scrollPosition_" + pathName, scrollPosition.toString());
                }
                if (sessionStorage["scrollPosition_" + pathName]) {
                    $(document).scrollTop(sessionStorage.getItem("scrollPosition_" + pathName));
                }
            });
    

提交回复
热议问题