如何使用JavaScript滚动到页面顶部?滚动条立即跳到页面顶部也是可取的,因为我不希望实现平滑滚动。


当前回答

试试这个

<script>
  $(function(){
   $('a').click(function(){
    var href =$(this).attr("href");
   $('body, html').animate({
     scrollTop: $(href).offset().top
     }, 1000)
  });
 });
 </script>

其他回答

非jQuery解决方案/纯JavaScript:

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

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

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

如果您想设置滚动动作的动画,则不需要javascript、event!

CSS:

html {
    scroll-behavior: smooth;
}

HTML格式:

<html>
  <body>
     <a id="top"></a>
     <!-- your document -->
     <a href="#top">Jump to top of page</a>
  </body>
</html>

TypeScript中的等效解决方案可能如下

   window.scroll({
      top: 0,
      left: 0,
      behavior: 'smooth'
    });

你不需要JQuery。只需调用脚本

window.location = '#'

单击“转到顶部”按钮

示例演示:

输出.jsbin.com/fakumo#

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