Scroll to the top of the page using JavaScript?

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

提交回复
热议问题