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


当前回答

如果您想滚动到具有ID的任何元素,请尝试以下操作:

$('a[href^="#"]').bind('click.smoothscroll',function (e) {
    e.preventDefault();
    var target = this.hash;
    $target = $(target);
    $('html, body').stop().animate({
        'scrollTop': $target.offset().top
    }, 700, 'swing', function () {
        window.location.hash = target;
    });
});``

其他回答

非jQuery解决方案/纯JavaScript:

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

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

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

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

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

尝试以下代码:

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

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

时间=>毫秒,定义滚动速度。

<script>

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

html格式

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