csdnceshi65
larry*wei
2009-07-17 17:59
采纳率: 0%
浏览 568

使用 javascript / jquery 滚动到页面顶部?

I've a <button> on the page, when this button is pressed a hidden <div> is shown using jQuery.

How do I scroll to the top of the page using a JavaScript/jQuery command in that function? It is desirable even if the scroll bar instantly jumps to the top. I'm not looking for a smooth scrolling.

转载于:https://stackoverflow.com/questions/1144805/scroll-to-the-top-of-the-page-using-javascript-jquery

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

30条回答 默认 最新

  • csdnceshi79
    python小菜 2009-07-17 18:42
    已采纳

    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.
    点赞 评论
  • csdnceshi60
    ℡Wang Yan 2009-07-17 18:09

    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.

    点赞 评论
  • csdnceshi72
    谁还没个明天 2009-07-17 18:51

    You don't need jQuery to do this. A standard HTML tag will suffice...

    <div id="jump_to_me">
        blah blah blah
    </div>
    
    <a target="#jump_to_me">Click Here To Destroy The World!</a>
    
    点赞 评论
  • csdnceshi53
    Lotus@ 2009-07-17 19:43

    If you do want smooth scrolling, try something like this:

    $("a[href='#top']").click(function() {
      $("html, body").animate({ scrollTop: 0 }, "slow");
      return false;
    });
    

    That will take any <a> tag whose href="#top" and make it smooth scroll to the top.

    点赞 评论
  • weixin_41568131
    10.24 2010-09-01 13:01

    With window.scrollTo(0, 0); is very fast
    so i tried the Mark Ursino example, but in Chrome nothing happens
    and i found this

    $('.showPeriodMsgPopup').click(function(){
        //window.scrollTo(0, 0);
        $('html').animate({scrollTop:0}, 'slow');//IE, FF
        $('body').animate({scrollTop:0}, 'slow');//chrome, don't know if Safari works
        $('.popupPeriod').fadeIn(1000, function(){
            setTimeout(function(){$('.popupPeriod').fadeOut(2000);}, 3000);
        });
    });
    

    tested all 3 browsers and it works
    i'm using blueprint css
    this is when a client clicks "Book now" button and doesn't have the rental period selected, slowly moves to the top where the calendars are and opens a dialog div pointing to the 2 fields, after 3sec it fades

    点赞 评论
  • csdnceshi59
    ℙℕℤℝ 2011-12-01 06:51

    Try this

    <script>
        $(window).scrollTop(100);
    </script>
    
    点赞 评论
  • csdnceshi59
    ℙℕℤℝ 2012-04-23 09:53

    All of these suggestions work great for various situations. For those who find this page through a search, one can also give this a try. JQuery, no plug-in, scroll to element.

    $('html, body').animate({
        scrollTop: $("#elementID").offset().top
    }, 2000);
    
    点赞 评论
  • csdnceshi74
    7*4 2012-05-21 07:45

    Try this to scroll on top

    <script>
     $(document).ready(function(){
        $(window).scrollTop(0);
    });
    </script>
    
    点赞 评论
  • csdnceshi54
    hurriedly% 2012-07-31 20:53

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

    点赞 评论
  • csdnceshi75
    衫裤跑路 2014-01-30 16:25

    Non-jQuery solution / pure JavaScript:

    document.body.scrollTop = document.documentElement.scrollTop = 0;
    
    点赞 评论
  • weixin_41568110
    七度&光 2014-02-01 19:35

    You can try using JS as in this Fiddle http://jsfiddle.net/5bNmH/1/

    Add the "Go to top" button in your page footer:

    <footer>
        <hr />
        <p>Just some basic footer text.</p>
        <!-- Go to top Button -->
        <a href="#" class="go-top">Go Top</a>
    </footer>
    
    点赞 评论
  • csdnceshi62
    csdnceshi62 2014-02-14 16:44
    <script>
    
      $("a[href='#top']").click(function() {
         $("html, body").animate({ scrollTop: 0 }, "slow");
         return false;
      });
    </script>
    

    in html

    <a href="#top">go top</a>
    
    点赞 评论
  • csdnceshi65
    larry*wei 2014-05-13 16:53

    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.

    点赞 评论
  • csdnceshi64
    游.程 2014-07-24 06:52
    <script>
    $(function(){
       var scroll_pos=(0);          
       $('html, body').animate({scrollTop:(scroll_pos)}, '2000');
    });
    </script>
    

    Edit:

    $('html, body').animate({scrollTop:(scroll_pos)}, 2000);
    
    点赞 评论
  • csdnceshi52
    妄徒之命 2014-10-02 10:00

    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

    点赞 评论
  • csdnceshi80
    胖鸭 2014-10-31 18:56

    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();
    }
    
    点赞 评论
  • csdnceshi75
    衫裤跑路 2014-11-21 21:11
    function scrolltop() {
    
        var offset = 220;
        var duration = 500;
    
        jQuery(window).scroll(function() {
            if (jQuery(this).scrollTop() > offset) {
                jQuery('#back-to-top').fadeIn(duration);
            } else {
                jQuery('#back-to-top').fadeOut(duration);
            }
        });
    
        jQuery('#back-to-top').click(function(event) {
            event.preventDefault();
            jQuery('html, body').animate({scrollTop: 0}, duration);
            return false;
        });
    }
    
    点赞 评论
  • csdnceshi66

    The old #top can do the trick

    document.location.href = "#top";
    

    Works fine in FF, IE and Chrome

    点赞 评论
  • weixin_41568126
    乱世@小熊 2015-05-29 10:49

    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));
        }
    })();
    
    点赞 评论
  • csdnceshi66

    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.

    点赞 评论
  • weixin_41568134
    MAO-EYE 2015-10-19 03:22

    Active all Browser. Good luck

    var process;
            var delay = 50; //milisecond scroll top
            var scrollPixel = 20; //pixel U want to change after milisecond
            //Fix Undefine pageofset when using IE 8 below;
            function getPapeYOfSet() {
                var yOfSet = (typeof (window.pageYOffset) === "number") ? window.pageYOffset : document.documentElement.scrollTop;
                return yOfSet;
            }
    
    
    
            function backToTop() {
                process = setInterval(function () {
                    var yOfSet = getPapeYOfSet();
                    if (yOfSet === 0) {
                        clearInterval(process);
                    } else {
                        window.scrollBy(0, -scrollPixel);
                    }
                }, delay);
            }
    
    点赞 评论
  • weixin_41568184
    叼花硬汉 2015-12-27 22:18

    Try this

    <script>
      $(function(){
       $('a').click(function(){
        var href =$(this).attr("href");
       $('body, html').animate({
         scrollTop: $(href).offset().top
         }, 1000)
      });
     });
     </script>
    
    点赞 评论
  • weixin_41568183
    零零乙 2016-03-20 09:42

    Why don't you use JQuery inbuilt function scrollTop :

    $('html, body').scrollTop(0);//For scrolling to top
    
    $("body").scrollTop($("body")[0].scrollHeight);//For scrolling to bottom
    

    Short and simple!

    点赞 评论
  • weixin_41568183
    零零乙 2017-08-08 07:42

    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.

    点赞 评论
  • csdnceshi72
    谁还没个明天 2017-09-11 10:37

    If you want to do smooth scrolling, please try this:

    $("a").click(function() {
         $("html, body").animate({ scrollTop: 0 }, "slow");
         return false;
    });
    

    Another solution is JavaScript window.scrollTo method :

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

    Parameters :

    • x-value is the pixel along the horizontal axis.
    • y-value is the pixel along the vertical axis.
    点赞 评论
  • csdnceshi78
    程序go 2017-09-27 11:31

    Simply use this script for scroll to top direct.

    <script>
    $(document).ready(function(){
        $("button").click(function(){
            ($('body').scrollTop(0));
        });
    });
    </script>
    
    点赞 评论
  • weixin_41568110
    七度&光 2018-02-14 12:21

    None of the answers above will work in SharePoint 2016.

    It has to be done like this : https://sharepoint.stackexchange.com/questions/195870/

    var w = document.getElementById("s4-workspace");
    w.scrollTop = 0;
    
    点赞 评论
  • csdnceshi63
    elliott.david 2018-04-19 05:13

    This will work:

    window.scrollTo(0, 0);

    点赞 评论
  • csdnceshi54
    hurriedly% 2018-05-09 08:46

    Motivation

    This simple solution works natively and implements a smooth scroll to any position.

    It avoids using anchor links (those with #) that, in my opinion, are useful if you want to link to a section, but are not so comfortable in some situations, specially when pointing to top which could lead to two different URLs pointing to the same location (http://www.example.org and http://www.example.org/#).

    Solution

    Put an id to the tag you want to scroll to, for example your first section, which answers this question, but the id could be placed everywhere in the page.

    <body>
      <section id="top">
        <!-- your content -->
      </section>
      <div id="another"><!-- more content --></div>
    

    Then as a button you can use a link, just edit the onclick attribute with a code like this.

    <a onclick="document.getElementById('top').scrollIntoView({ behavior: 'smooth', block: 'start', inline: 'nearest' })">Click me</a>
    

    Where the argument of document.getElementById is the id of the tag you want to scroll to after click.

    点赞 评论
  • csdnceshi50
    三生石@ 2018-07-14 07:45

    $(".scrolltop").click(function() {
      $("html, body").animate({ scrollTop: 0 }, "slow");
      return false;
    });
    .section{
     height:400px;
    }
    .section1{
      background-color: #333;
    }
    .section2{
      background-color: red;
    }
    .section3{
      background-color: yellow;
    }
    .section4{
      background-color: green;
    }
    .scrolltop{
      position:fixed;
      right:10px;
      bottom:10px;
      color:#fff;
    }
    <html>
    <head>
    <title>Scroll top demo</title>
    <script src="https://code.jquery.com/jquery-3.3.1.js"></script>
    </head>
    <body>
    <div class="content-wrapper">
    <div class="section section1"></div>
    <div class="section section2"></div>
    <div class="section section3"></div>
    <div class="section section4"></div>
    <a class="scrolltop">Scroll top</a>
    </div>
    
    </body>
    </html>

    </div>
    
    点赞 评论

相关推荐