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


当前回答

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

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

其他回答

你可以尝试在这个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>

如果您不希望平滑滚动,您可以在启动平滑滚动动画时立即欺骗并停止它……如下所示:

   $(document).ready(function() {
      $("a[href='#top']").click(function() {
          $("html, body").animate({ scrollTop: 0 }, "1");              
          $('html, body').stop(true, true);

          //Anything else you want to do in the same action goes here

          return false;                              
      });
  });

我不知道它是否被推荐/允许,但它有效:)

你什么时候用这个?我不确定,但也许当您想使用Jquery一键制作一件事情的动画,而不使用动画制作另一件事情时?即打开页面顶部的管理登录面板中的幻灯片,然后立即跳到顶部查看。

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

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:

(function smoothscroll(){
    var currentScroll = document.documentElement.scrollTop || document.body.scrollTop;
    if (currentScroll > 0) {
         window.requestAnimationFrame(smoothscroll);
         window.scrollTo (0,currentScroll - (currentScroll/5));
    }
})();

有趣的是,其中大多数根本不适合我,所以我使用了jQuery-ScrollTo.js:

wrapper.find(".jumpToTop").click(function() {
    $('#wrapper').ScrollTo({
        duration: 0,
        offsetTop: -1*$('#container').offset().top
    });
});

它奏效了$(document).sollTop()返回了0,而这个函数实际上起了作用。