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


当前回答

试试这个

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

其他回答

只需尝试,不需要其他插件/框架

document.getElementById(“jarscoolbtn”).addEventListener(“单击”,jarsrollfunction);函数jarrollfunction(){var body=document.body;//对于Safarivar html=document.documentElement;//Chrome、Firefox、IE和Operabody.scrollTop=0;html.scrollTop=0;}<button id=“jarscoolbtn”>滚动内容</button>html,正文{滚动行为:平滑;}

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

纯JavaScript解决方案:

function scrollToTop() {
  window.scrollTo({
    top: 0,
    behavior: 'smooth'
});

我在Codepen上编写了一个动画解决方案

此外,您可以尝试使用CSS滚动行为的另一种解决方案:smooth属性。

html {
    scroll-behavior: smooth;
}

@media (prefers-reduced-motion: reduce) {
    html {
        scroll-behavior: auto;
    }
}

如果您想滚动到具有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。只需调用脚本

window.location = '#'

单击“转到顶部”按钮

示例演示:

输出.jsbin.com/fakumo#

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