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


当前回答

为什么不使用JQuery内置函数scrollTop:

$('html, body').scrollTop(0);//For scrolling to top

$("body").scrollTop($("body")[0].scrollHeight);//For scrolling to bottom

简短而简单!

其他回答

纯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;
    }
}

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

   $(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.querySelector('.sample-modal .popup-cta').scrollIntoView(true);
document.querySelector('.sample-modal').style.scrollPadding = '50px'; //to move to the top when scrolled up.

您可以使用javascript的内置函数scrollTo:

函数滚动(){window.scrollTo({顶部:0,行为:“平滑”});}<button onclick=“scroll”>滚动</button>

如果您想设置滚动动作的动画,则不需要javascript、event!

CSS:

html {
    scroll-behavior: smooth;
}

HTML格式:

<html>
  <body>
     <a id="top"></a>
     <!-- your document -->
     <a href="#top">Jump to top of page</a>
  </body>
</html>