JQuery滚动到页面顶部

有没有办法以编程方式使用jQuery滚动到页面顶部? 我目前正在尝试使用以下代码执行此操作,但它无法正常工作。 我目前正在使用Firefox,

$(window).scrollTop($(document).height()); 

试试这个:

 $('html, body').animate({scrollTop: '0px'}, 300); 

您可以使用0而不是300来实现此function,但这样可以实现快速自动滚动效果。

只需添加一个片段给Nick的好答案。 这仅在用户向下滚动页面后显示“滚动到顶部”元素,即Pinterest样式。

  $("#scroll_to_top_button").hide(); // hide on page load $(window).bind('scroll', function(){ if($(this).scrollTop() > 200) { // show after 200 px of user scrolling $("#scroll_to_top").slideDown("fast"); } }); 

这里不需要jQuery。 使用原生:

window.scrollTo(x-coordinate, y-coordinate);

请注意,这无法控制jQuery提供的动画部分(持续时间等)

 $('a[href^="#"]').on('click', function(event) { var target = $(this.getAttribute('href')); if( target.length ) { event.preventDefault(); $('html, body').stop().animate({ scrollTop: target.offset().top }, 1000); } 

});

将其添加到HTML

 
Click to scroll up