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


当前回答

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

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

其他回答

试试这个

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

使用window.scrowlTo(0,0);速度非常快所以我尝试了Mark Ursino的例子,但在Chrome中什么都没有发生我找到了这个

$('.showPeriodMsgPopup').click(function(){
    //window.scrollTo(0, 0);
    $('html').animate({scrollTop:0}, 'slow');//IE, FF
    $('body').animate({scrollTop:0}, 'slow');//chrome, don't know if Safari works
    $('.popupPeriod').fadeIn(1000, function(){
        setTimeout(function(){$('.popupPeriod').fadeOut(2000);}, 3000);
    });
});

测试了所有3种浏览器,并正常工作我正在使用蓝图css这是当客户点击“立即预订”按钮并且没有选择租赁期时,慢慢移动到日历所在的顶部,并打开一个指向2个字段的对话框div,3秒后它会消失

如果您确实想要平滑滚动,请尝试以下操作:

$("a[href='#top']").click(function() {
  $("html, body").animate({ scrollTop: 0 }, "slow");
  return false;
});

这将接受href=“#top”的任何<a>标记,并使其平滑滚动到顶部。

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

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