Prevent Refresh 'Jump' with Javascript

2020-05-26 11:42发布

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 to prevent this?

I have looked at two options and neither are consistent across Webkit / Firefox.

    window.scrollTo(0, 1);
    $('html, body').animate({ scrollTop: 0 }, 0);

Any ideas?

You can check a google search result for an example.

5条回答
在下西门庆
2楼-- · 2020-05-26 12:23

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>
查看更多
叼着烟拽天下
3楼-- · 2020-05-26 12:31

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);
});
查看更多
▲ chillily
4楼-- · 2020-05-26 12:33

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

查看更多
beautiful°
5楼-- · 2020-05-26 12:38

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.

查看更多
Bombasti
6楼-- · 2020-05-26 12:49

Works for me:

// Scroll top bro
window.onload = function() {
 setTimeout (function () {
  scrollTo(0,0);
 }, 0);
}
查看更多
登录 后发表回答