JQuery 滚动到页面顶部

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2275274/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 13:09:34  来源:igfitidea点击:

JQuery scroll to top of page

jquery

提问by medium

Is there a way to programmatically scroll to the top of a page with jQuery? I am currently trying to do this with the following code but it is not working. I am using Firefox currently,

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

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

回答by Nick Craver

Try this:

尝试这个:

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

You can do this with 0instead of 300to be instant, but this gives a quick auto-scroll effect.

您可以使用0而不是300立即执行此操作,但这会提供快速自动滚动效果。

回答by Banjer

Just adding a snippet to Nick's nice answer. This shows your "scroll to top" element only after the user has scrolled down the page some, i.e. Pinterest-style.

只需在尼克的好答案中添加一个片段即可。这仅在用户向下滚动页面后才会显示您的“滚动到顶部”元素,即 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");
   }
  });

回答by luigi7up

No need for jQuery here. Use native:

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

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

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

Note that this has no control over animate part (duration etc.) that jQuery provides

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

回答by subindas pm

$('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);
}

});

});

Add this to the HTML

将此添加到 HTML

<div id="top"></div>
<a href="#top">Click to scroll up</a>