Scroll to the top of the page using JavaScript?

后端 未结 30 1103
借酒劲吻你
借酒劲吻你 2020-11-22 03:18

How do I scroll to the top of the page using JavaScript? The scrollbar instantly jumping to the top of the page is desirable too as I\'m not looking to achieve smooth scroll

30条回答
  •  一生所求
    2020-11-22 03:45

    A lot of users recommend selecting both the html and body tags for cross-browser compatibility, like so:

    $('html, body').animate({ scrollTop: 0 }, callback);
    

    This can trip you up though if you're counting on your callback running only once. It will in fact run twice because you've selected two elements.

    If that is a problem for you, you can do something like this:

    function scrollToTop(callback) {
        if ($('html').scrollTop()) {
            $('html').animate({ scrollTop: 0 }, callback);
            return;
        }
    
        $('body').animate({ scrollTop: 0 }, callback);
    }
    

    The reason this works is in Chrome $('html').scrollTop() returns 0, but not in other browsers such as Firefox.

    If you don't want to wait for the animation to complete in the case that the scrollbar is already at the top, try this:

    function scrollToTop(callback) {
        if ($('html').scrollTop()) {
            $('html').animate({ scrollTop: 0 }, callback);
            return;
        }
    
        if ($('body').scrollTop()) {
            $('body').animate({ scrollTop: 0 }, callback);
            return;
        }
    
        callback();
    }
    

提交回复
热议问题