Force page scroll position to top at page refresh in HTML

前端 未结 13 1210
野的像风
野的像风 2020-12-02 07:57

I am building a website which I am publishing with divs. When I refresh the page after it was scrolled to position X, then the page is loaded with the scroll po

相关标签:
13条回答
  • 2020-12-02 08:41

    To reset window scroll back to top, $(window).scrollTop(0) in the beforeunload event does the tricks, however, I tested in Chrome 80 it will go back to the old location after the reload.

    To prevent that, set the history.scrollRestoration to "manual".

    //Reset scroll top
    
    history.scrollRestoration = "manual";
    
    $(window).on('beforeunload', function(){
          $(window).scrollTop(0);
    });
    
    0 讨论(0)
  • 2020-12-02 08:42

    You can do it using the scrollTop method on DOM ready:

    $(document).ready(function(){
        $(this).scrollTop(0);
    });
    
    0 讨论(0)
  • 2020-12-02 08:44

    For a simple plain JavaScript implementation:

    window.onbeforeunload = function () {
      window.scrollTo(0, 0);
    }

    0 讨论(0)
  • 2020-12-02 08:50

    The answer here(scrolling in $(document).ready) doesn't work if there is a video in the page. In that case the page is scrolled after this event is fired, overriding our work.

    Best answer should be:

    $(window).on('beforeunload', function(){
        $(window).scrollTop(0);
    });
    
    0 讨论(0)
  • 2020-12-02 08:50

    This is one of the best way to do so:

    <script>
    $(window).on('beforeunload', function() {
      $('body').hide();
      $(window).scrollTop(0);
    });
    </script>

    0 讨论(0)
  • 2020-12-02 08:53
    <script> location.hash = (location.hash) ? location.hash : " "; </script>
    

    Put the above script in <head> tag of your html. Not sure how single page apps behave! But sure works like charm in regular pages.

    0 讨论(0)
提交回复
热议问题