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


当前回答

尝试以下代码:

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

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

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

其他回答

真的很奇怪:这个问题已经活跃了五年了,但仍然没有一个普通的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

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

编辑:

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

另一种上下边距滚动方式:

window.scrollTo({ top: 100, left: 100, behavior: 'smooth' });

非jQuery解决方案/纯JavaScript:

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

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

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

尝试以下代码:

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

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

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