Scroll to the top of the page using JavaScript?

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

    You could simply use a target from your link, such as #someid, where #someid is the div's id.

    Or, you could use any number of scrolling plugins that make this more elegant.

    http://plugins.jquery.com/project/ScrollTo is an example.

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

    You dont need JQuery. Simply you can call the script

    window.location = '#'
    

    on click of the "Go to top" button

    Sample demo:

    output.jsbin.com/fakumo#

    PS: Don't use this approach, when you are using modern libraries like angularjs. That might broke the URL hashbang.

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

    smooth scroll, pure javascript:

    (function smoothscroll(){
        var currentScroll = document.documentElement.scrollTop || document.body.scrollTop;
        if (currentScroll > 0) {
             window.requestAnimationFrame(smoothscroll);
             window.scrollTo (0,currentScroll - (currentScroll/5));
        }
    })();
    
    0 讨论(0)
  • 2020-11-22 03:50

    This will work:

    window.scrollTo(0, 0);

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

    If you don't want smooth scrolling, you can cheat and stop the smooth scrolling animation pretty much as soon as you start it... like so:

       $(document).ready(function() {
          $("a[href='#top']").click(function() {
              $("html, body").animate({ scrollTop: 0 }, "1");              
              $('html, body').stop(true, true);
    
              //Anything else you want to do in the same action goes here
    
              return false;                              
          });
      });
    

    I've no idea whether it's recommended/allowed, but it works :)

    When would you use this? I'm not sure, but perhaps when you want to use one click to animate one thing with Jquery, but do another without animation? ie open a slide-in admin login panel at the top of the page, and instantly jump to the top to see it.

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

    Pure JavaScript solution:

    function scrollToTop() {
      window.scrollTo({
        top: 0,
        behavior: 'smooth'
    });
    

    I write an animated solution on Codepen

    Also, you can try another solution with CSS scroll-behavior: smooth property.

    html {
        scroll-behavior: smooth;
    }
    
    @media (prefers-reduced-motion: reduce) {
        html {
            scroll-behavior: auto;
        }
    }
    
    0 讨论(0)
提交回复
热议问题