Force page scroll position to top at page refresh in HTML

前端 未结 13 1209
野的像风
野的像风 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:33

    The supercalifragilisticexpialidocious answer is:

    add this at the top of your js file or script tag

    document.documentElement.scrollTop = 0; // For Chrome, Firefox, IE and Opera
    
    document.body.scrollTop = 0; // For Safari
    
    0 讨论(0)
  • 2020-12-02 08:34

    Again, best answer is:

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

    (thats for non-jQuery, look up if you are searching for the JQ method)

    EDIT: a little mistake its "onbeforunload" :) Chrome and others browsers "remember" the last scroll position befor unloading, so if you set the value to 0,0 just before the unload of your page they will remember 0,0 and won't scroll back to where the scrollbar was :)

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

    Check the jQuery .scrollTop() function here

    It would look something like

    $(document).load().scrollTop(0);
    
    0 讨论(0)
  • 2020-12-02 08:37

    The answer here does not works for safari, document.ready is often fired too early.

    Ought to use the beforeunload event which prevent you form doing some setTimeout

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

    Instead of location.reload(), simply use location.href = location.href. It will not scroll to the previous position as location.reload() does.

    Note: This will not reload if there is any # in the URL

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

    did not work for me as google chrome would just scroll back down after the page finished loading. What I used was

    $(document).ready(function() {
        var url = window.location.href;
        console.log(url);
        if( url.indexOf('#') < 0 ) {
            window.location.replace(url + "#");
        } else {
            window.location.replace(url);
        }
    });
    

    // This loads the page with a # at the end. So it will always load at the top.

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