首页 文章

使用JavaScript / jQuery滚动到页面顶部?

提问于
浏览
1341

我在页面上有 <button> ,当按下此按钮时,使用jQuery显示隐藏的 <div> .

如何使用该函数中的JavaScript / jQuery命令滚动到页面顶部?即使滚动条立即跳到顶部也是可取的 . 我不是在寻找一个平滑的滚动 .

30 回答

  • 21

    真奇怪:这个问题现在已经活跃了五年了,而且仍然没有一个简单的JavaScript答案来动画滚动...所以你走了:

    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)
    

    如果您愿意,可以将其包装在函数中并通过 onclick 属性调用它 . 检查一下jsfiddle

    注意:这是一个非常基本的解决方案,可能不是最高效的解决方案 . 可以在这里找到一个非常详细的例子:https://github.com/cferdinandi/smooth-scroll

  • 9

    更流畅的动画解决方案:

    // this changes the scrolling behavior to "smooth"
    window.scrollTo({ top: 0, behavior: 'smooth' });
    

    参考:https://developer.mozilla.org/en-US/docs/Web/API/Window/scrollTo#Example

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

    在HTML中

    <a href="#top">go top</a>
    
  • 21

    您可以简单地使用链接中的目标,例如#someid,其中#someid是div的id .

    或者,您可以使用任何数量的滚动插件,使其更优雅 .

    http://plugins.jquery.com/project/ScrollTo就是一个例子 .

  • 5

    lot of users建议选择html和body标签以实现跨浏览器兼容性,如下所示:

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

    如果您指望只运行一次回调,这可能会让您失望 . 它实际上会运行两次因为你选择了两个元素 .

    如果这对您来说是个问题,您可以这样做:

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

    这可行的原因是Chrome $('html').scrollTop() 返回0,但在Firefox等其他浏览器中则不然 .

    如果您不希望在滚动条已位于顶部的情况下等待动画完成,请尝试以下操作:

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

    只需使用此脚本滚动到顶部直接 .

    <script>
    $(document).ready(function(){
        $("button").click(function(){
            ($('body').scrollTop(0));
        });
    });
    </script>
    
  • 16

    如果您不需要更改动画,那么您不需要使用任何特殊插件 - 我只使用本机JavaScript window.scrollTo方法 - 传入0,0会立即将页面滚动到左上角 .

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

    参数

    • x-coord是沿水平轴的像素 .

    • y-coord是沿垂直轴的像素 .

  • 1219

    平滑滚动,纯javascript:

    (function smoothscroll(){
        var currentScroll = document.documentElement.scrollTop || document.body.scrollTop;
        if (currentScroll > 0) {
             window.requestAnimationFrame(smoothscroll);
             window.scrollTo (0,currentScroll - (currentScroll/5));
        }
    })();
    
  • 13
    $(".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>
    
  • 23

    你不需要jQuery来做到这一点 . 标准HTML标签就足够了......

    <div id="jump_to_me">
        blah blah blah
    </div>
    
    <a target="#jump_to_me">Click Here To Destroy The World!</a>
    
  • 6

    如果你不想平滑滚动,你可以在你启动它时立即作弊并停止平滑滚动动画......就像这样:

    $(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;                              
          });
      });
    

    我不知道是否推荐/允许,但它的工作原理:)

    你什么时候用这个?我不确定,但也许当你想用一次点击用Jquery动画一个东西,但做另一个没有动画的东西?即打开页面顶部的滑入管理员登录面板,然后立即跳到顶部查看 .

  • 26

    试试这个

    <script>
        $(window).scrollTop(100);
    </script>
    
  • 4

    如果你想平滑滚动,请试试这个:

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

    另一个解决方案是JavaScript window.scrollTo方法:

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

    参数:

    • x-value是沿水平轴的像素 .

    • y值是沿垂直轴的像素 .

  • 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;
        });
    }
    
  • 10

    如果你想要平滑滚动,尝试这样的事情:

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

    这将采用任何 <a> 标签 href="#top" 并使其平滑滚动到顶部 .

  • 137

    非jQuery解决方案/纯JavaScript:

    document.body.scrollTop = document.documentElement.scrollTop = 0;
    
  • 13

    动机

    这个简单的解决方案可以本地工作,并实现平滑滚动到任何位置 .

    它避免使用锚链接(那些 # ),在我看来,如果你想链接到一个部分,但在某些情况下不太舒服,特别是当指向顶部时可能导致两个不同的URL指向相同的位置(http://www.example.orghttp://www.example.org/#) .

    解决方案

    将id添加到要滚动到的标记,例如您的第一部分,它可以回答此问题,但ID可以放在页面的任何位置 .

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

    然后作为一个按钮,你可以使用一个链接,只需用这样的代码编辑onclick属性 .

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

    document.getElementById 的参数是您要在单击后滚动到的标记的ID .

  • 7
    <script>
    $(function(){
       var scroll_pos=(0);          
       $('html, body').animate({scrollTop:(scroll_pos)}, '2000');
    });
    </script>
    

    编辑:

    $('html, body').animate({scrollTop:(scroll_pos)}, 2000);
    
  • 1840

    试试这段代码:

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

    div => 要移动滚动的Dom元素 .

    time => 毫秒,定义滚动的速度 .

  • 4

    你不需要JQuery . 您只需调用脚本即可

    window.location = '#'
    

    点击“转到顶部”按钮

    示例演示:

    output.jsbin.com/fakumo#

    PS:当你使用像angularjs这样的现代库时,不要使用这种方法 . 这可能会破坏URL hashbang .

  • 34

    上述答案都不适用于SharePoint 2016 .

    它必须这样做:https://sharepoint.stackexchange.com/questions/195870/

    var w = document.getElementById("s4-workspace");
    w.scrollTop = 0;
    
  • 4

    活动所有浏览器 . 祝好运

    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);
            }
    
  • 9

    This will work:

    window.scrollTo(0, 0);

  • 14

    为什么不使用JQuery内置函数scrollTop:

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

    简短而简单!

  • 9

    旧的 #top 可以做到这一点

    document.location.href = "#top";
    

    在FF,IE和铬

  • 3

    window.scrollTo(0, 0); 非常快
    所以我尝试了Mark Ursino的例子,但在Chrome中没有任何反应
    我发现了这个

    $('.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);
        });
    });
    

    测试了所有3个浏览器并且它有效
    我正在使用蓝图css
    这是当客户点击"Book now"按钮并且没有选择租借期间时,慢慢移动到日历所在的顶部并打开指向2个字段的对话框div,3秒后它会消失

  • 26

    $(document).scrollTop(0); 也有效 .

  • 6

    您可以尝试使用JS,因为这个小提琴http://jsfiddle.net/5bNmH/1/

    在页脚中添加“转到顶部”按钮:

    <footer>
        <hr />
        <p>Just some basic footer text.</p>
        <!-- Go to top Button -->
        <a href="#" class="go-top">Go Top</a>
    </footer>
    
  • 52

    Try this to scroll on top

    <script>
     $(document).ready(function(){
        $(window).scrollTop(0);
    });
    </script>
    
  • 4

    所有这些建议都适用于各种情况 . 对于那些通过搜索找到此页面的人,也可以尝试this . JQuery,没有插件,滚动到元素 .

    $('html, body').animate({
        scrollTop: $("#elementID").offset().top
    }, 2000);
    

相关问题