jQuery 在页面加载时动画滚动到 ID
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6682451/
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
Animate scroll to ID on page load
提问by Adi
Im tring to animate the scroll to a particular ID on page load. I have done lots of research and came across this:
我想在页面加载时将滚动动画设置为特定 ID。我做了很多研究,发现了这个:
$("html, body").animate({ scrollTop: $('#title1').height() }, 1000);
but this seems to start from the ID and animate to the top of the page?
但这似乎是从 ID 开始并动画到页面顶部?
The HTML (which is half way down the page) is simply:
HTML(位于页面的一半)很简单:
<h2 id="title1">Title here</h2>
回答by BumbleB2na
You are only scrolling the height of your element. offset()returns the coordinates of an element relative to the document, and top
param will give you the element's distance in pixels along the y-axis:
您只是在滚动元素的高度。offset()返回元素相对于文档的坐标,top
param 将为您提供元素沿 y 轴的像素距离:
$("html, body").animate({ scrollTop: $('#title1').offset().top }, 1000);
And you can also add a delay to it:
您还可以为其添加延迟:
$("html, body").delay(2000).animate({scrollTop: $('#title1').offset().top }, 2000);
回答by Vladimir Vovk
Pure javascript solution with scrollIntoView()function:
带有scrollIntoView()函数的纯 javascript 解决方案:
document.getElementById('title1').scrollIntoView({block: 'start', behavior: 'smooth'});
<h2 id="title1">Some title</h2>
P.S. 'smooth' parameter now works from Chrome 61 as julien_cmentioned in the comments.
PS 'smooth' 参数现在可以在 Chrome 61 中使用,如评论中提到的julien_c。
回答by AleX gRey
$(jQuery.browser.webkit ? "body": "html").animate({ scrollTop: $('#title1').offset().top }, 1000);
回答by Eugene Tiurin
There is a jquery plugin for this. It scrolls document to a specific element, so that it would be perfectly in the middle of viewport. It also supports animation easings so that the scroll effect would look super smooth. Check this link.
有一个 jquery 插件。它将文档滚动到特定元素,使其完美地位于视口的中间。它还支持动画缓动,使滚动效果看起来非常平滑。检查此链接。
In your case the code is
在你的情况下,代码是
$("#title1").animatedScroll({easing: "easeOutExpo"});
回答by Akhil
try with following code. make elements with class name page-scrolland keep id name to href
of corresponding links
尝试使用以下代码。使元素具有类名page-scroll并保留href
相应链接的id 名称
$('a.page-scroll').bind('click', function(event) {
var $anchor = $(this);
$('html, body').stop().animate({
scrollTop: ($($anchor.attr('href')).offset().top - 50)
}, 1250, 'easeInOutExpo');
event.preventDefault();
});
回答by m.m
for simple Scroll, use following style
对于简单的滚动,使用以下样式
height: 200px; overflow: scroll;
高度:200px;溢出:滚动;
and use this style class which div or section you want to show scroll
并使用此样式类要显示滚动的 div 或部分