简体   繁体   中英

JavaScript: Is there an event like “restoring scroll position after refresh”? Is there any way to use/create it?

When you scroll a webpage, and refresh it, the scroll will jump to the place it was before the refresh. I have some scroll-related JavaScript, which modifies the visual state of the webpage on the "scroll" event, but it doesn't register the "scroll position restoring" after refresh. Currently I worked around it by simply setting setTimeout , waiting a while, and then reading the scroll position and running my code, but it isn't right. Is there any better way to do this?

If you need to scroll after refresh its strange behave because when you refresh all website loading from scratch. What can be done maybe to save it on localStorage the position and after the page loaded do scroll:

 window.onbeforeunload = function() {
    localStorage.setItem('position',window.pageYOffset);
}


    $(window).on('load', function(){

         window.scrollTo(0,localStorage.getItem('position')||0);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM