Prevent Refresh 'Jump' with Javascript

后端 未结 5 817
滥情空心
滥情空心 2021-02-05 17:20

I\'ve noticed that if you are on a page and you have scrolled down a good bit, if you refresh the page, most browsers will jump you back down to your position. Is there any way

相关标签:
5条回答
  • 2021-02-05 17:49

    I see no reason why this shouldn't work in all browsers, seems to work for me (with only one function for window.onload, use more and there could be problems) ?

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

    To make it work when back button is clicked aswell, maybe something like this:

    <body onunload="">
    <script type="text/javascript">
        window.onload = function() {
           scrollTo(0,0);
        }
    </script>
    //content here
    </body>
    
    0 讨论(0)
  • 2021-02-05 17:49

    Works for me:

    // Scroll top bro
    window.onload = function() {
     setTimeout (function () {
      scrollTo(0,0);
     }, 0);
    }
    
    0 讨论(0)
  • 2021-02-05 18:01

    Something like below works for me, create some item that can be focused and focus it to scroll page.

    In this case it will scroll back to top after refresh the page.

    Tested on latest IE/FF/Chrome.

        <html>
        <head>
            <script type="text/javascript">
                window.onload = function () {
                    setTimeout (function () {
                        // use both 'a' and 'button' because 'a' not work as expected on some browsers
                        document.getElementById('top_anchor').focus();
                        document.getElementById('top_anchor_btn').focus();
                    }, 0);
                }
            </script>
        </head>
        <body>
            <a id="top_anchor" href="" style="width: 1px; height: 1px; position: absolute; top: 0px; left: -1000px;"></a>
            <button id="top_anchor_btn" href="" style="width: 1px; height: 1px; position: absolute; top: 0px; left: -1000px;"></button>
    
            <div> top </div>
            <div style="width: 500px; height: 2000px; background-color: #83FEBC;">
                content
            </div>
        </body>
    </html>
    

    Regards,

    Ben

    0 讨论(0)
  • 2021-02-05 18:11

    Just to update what @josetapadas said, for recent versions it would be better to use the unload function instead of beforeunload this will be

    $(window).on('unload', function() {
    $(window).scrollTop(0);
    });
    
    0 讨论(0)
  • 2021-02-05 18:12

    On Chrome, even if you force scrollTop to 0 it will jump afterwards after the first scroll event.

    You should bind the scroll to this:

    $(window).on('beforeunload', function() {
        $(window).scrollTop(0);
    });
    

    So the browser is tricked to believe that it was on the beginning before the refresh.

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