Javascript page reload while maintaining current window position

前端 未结 4 926
旧巷少年郎
旧巷少年郎 2020-12-09 06:48

How do I refresh the page using Javascript without the page returning to the top.

My page refreshes using a timer but the problem is it goes back to the top every ti

4条回答
  •  攒了一身酷
    2020-12-09 07:12

    If there is a certain set of specific sections of the page that are possible initial "scroll to" points, then you can assign those sections CSS ids and refresh the page with an appended ID hash at the end. For example, window.location = http://example.com#section2 will reload the page and automatically scroll it down to the element with the id "section2".

    If it's not that specific, you can grab the current scroll position prior to refresh using jQuery's .scrollTop() method on the window: $(window).scrollTop(). You can then append this to the refresh URL, and include JS on the page that checks for this in order to automatically scroll to the correct position upon page load:

    Grab current scroll position

    var currentScroll = $(window).scrollTop();
    window.location = 'http://example.com#' + currentScroll;
    

    JS that must run when DOM is ready in order to check for a currentScroll hash

    $(function(){
        if(window.location.hash !== ''){
            var scrollPos = parseInt(window.location.hash.substring(1),10);
            $(window).scrollTo(scrollPos);
        }
    });
    

    If you don't like the idea of modifying the URL in the address bar (because you really want to hide what you're doing from the user for some reason), you could store the scrollTo() value in a cookie instead of the URL.

提交回复
热议问题