jQuery Animate Div 滚动回到顶部

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10689573/
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 09:40:02  来源:igfitidea点击:

jQuery Animate Div Scroll back to top

jquery

提问by Joe

I have a div which has the content:

我有一个包含以下内容的 div:

<div id="First">There are lots of content in here. Blah Blah Blah...</div>

The divhas a style attribute of overflow:auto;so if any content were to overflow, a scrollbar would appear. I have a button inside the div at the end of the content.

div具有的样式属性overflow:auto;,所以如果任何内容都溢出,滚动条就会出现。我在内容末尾的 div 中有一个按钮。

Since the content inside the div could allow for a deep scroll, is there anyway, that on click of the button it will move the scroll back to the top of the div?

由于 div 内的内容可以允许深度滚动,无论如何,单击按钮会将滚动条移回 div 的顶部吗?

回答by lukas.pukenis

Yes. Use scrollTop

是的。使用滚动顶部

Just provide your element and a value of 0 like this:

只需提供您的元素和 0 值,如下所示:

$('#id').scrollTop(0);

You can also animate the scrolling back to top like this:

您还可以像这样滚动回到顶部的动画:

$('#id').animate({
   scrollTop: 0
}, 'slow');

回答by Alp

You do not need jQuery (or even JavaScript) for this.

为此,您不需要 jQuery(甚至 JavaScript)。

DEMO

演示

Define an anchor name:

定义一个锚名称:

<a name="top"></a>

And create a link to this anchor at the bottom:

并在底部创建一个指向此锚点的链接:

<a href="#top">back to top</a>?

回答by DisplayName

Use ScrollTopif you are dealing with a y-overflow and/or ScrollLeftfor x-overflow.

如果您正在处理 y-overflow 和/或ScrollLeftfor x-overflow,请使用ScrollTop

$('#yourbuttonid').click(function() {
    $('#First').scrollTop(0);//for vertical scroll
    $('#First').scrollLeft(0);//for horizontal scroll
});

回答by lbstr

$('#scrollToTopButton').click(function(){
    $('#First').scrollTop(0);
});

回答by Tiquelou

OVERKILL!!! Using scrollTop, or jquery for that matter... for such a simple task may not be advisable. Use anchors instead:

超杀!!!使用 scrollTop 或 jquery ……对于这样一个简单的任务可能是不可取的。改用锚点:

<a name="pageTop"></a>
....
<a href="#pageTop">TOP</a>

Or is there something more you want to do / achieve?

或者你还有什么想做/想要实现的吗?