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


当前回答

尝试此操作以在顶部滚动

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

其他回答

你可以尝试在这个Fiddle中使用JShttp://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>
<script>

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

html格式

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

最短的

location='#'

这种解决方案是对pollinrata答案的改进,并且有一些缺点:没有平滑的滚动和更改页面位置,但最短

平滑动画的更好解决方案:

// 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

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

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