Scroll to the top of the page using JavaScript?

后端 未结 30 1093
借酒劲吻你
借酒劲吻你 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:51

    Simply use this script for scroll to top direct.

    <script>
    $(document).ready(function(){
        $("button").click(function(){
            ($('body').scrollTop(0));
        });
    });
    </script>
    
    0 讨论(0)
  • 2020-11-22 03:52

    Try this code:

    $('html, body').animate({
        scrollTop: $("div").offset().top
    }, time);
    

    div => Dom Element where you want to move scroll.

    time => milliseconds, define the speed of the scroll.

    0 讨论(0)
  • 2020-11-22 03:54

    If you don't need the change to animate then you don't need to use any special plugins - I'd just use the native JavaScript window.scrollTo method -- passing in 0,0 will scroll the page to the top left instantly.

    window.scrollTo(x-coord, y-coord);
    

    Parameters

    • x-coord is the pixel along the horizontal axis.
    • y-coord is the pixel along the vertical axis.
    0 讨论(0)
  • 2020-11-22 03:55

    $(document).scrollTop(0); also works.

    0 讨论(0)
  • 2020-11-22 03:56

    Really strange: This question is active for five years now and there is still no vanilla JavaScript answer to animate the scrolling… So here you go:

    var scrollToTop = window.setInterval(function() {
        var pos = window.pageYOffset;
        if ( pos > 0 ) {
            window.scrollTo( 0, pos - 20 ); // how far to scroll on each step
        } else {
            window.clearInterval( scrollToTop );
        }
    }, 16); // how fast to scroll (this equals roughly 60 fps)
    

    If you like, you can wrap this in a function and call that via the onclick attribute. Check this jsfiddle

    Note: This is a very basic solution and maybe not the most performant one. A very elaborated example can be found here: https://github.com/cferdinandi/smooth-scroll

    0 讨论(0)
  • 2020-11-22 03:56

    Try this

    <script>
        $(window).scrollTop(100);
    </script>
    
    0 讨论(0)
提交回复
热议问题