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


当前回答

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

   $(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一键制作一件事情的动画,而不使用动画制作另一件事情时?即打开页面顶部的管理登录面板中的幻灯片,然后立即跳到顶部查看。

其他回答

如果你不需要更改动画,那么你就不需要使用任何特殊的插件——我只需要使用原生JavaScript window.scrollTo()方法——传入0,0将立即将页面滚动到左上角。

window.scrollTo(xCoord, yCoord);

参数

xCoord是沿水平轴的像素。yCoord是沿垂直轴的像素。

document.getElementById(“elem”)scrollIntoView();

如果您想滚动到具有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;
    });
});``

滚动到带有动画的页面顶部:

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

试试这个

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