javascript 5 秒后自动将页面滚动到 div
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15484367/
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
Automatic scroll the page to a div after 5 seconds
提问by giovanni
I'm new in javascript, now I'm trying to do that, as the title, I've a page which has a div at the top that is as big as the page with a video in it, followed by several sections like this:
我是 javascript 新手,现在我正在尝试这样做,作为标题,我有一个页面,顶部有一个 div,与其中包含视频的页面一样大,然后是几个部分,例如这:
<div id="first" style="height:100%; width:100%"></div>
<section id="second" style="height:100%; width:100%"></section>
<section id="third" style="height:100%; width:100%"></section>
Now I need 5 seconds after the page is loaded to scroll automatically the page to #second. I've tried many ways but have failed and haven't found nothing that works properly.
现在我需要在页面加载 5 秒后自动将页面滚动到 #second。我尝试了很多方法,但都失败了,也没有发现任何可以正常工作的方法。
Thanks
谢谢
回答by zzzzBov
I'm feeling generous, so I'll just give you the code this time.
我觉得很慷慨,所以这次我只给你代码。
$(window).load(function () {
//normally you'd wait for document.ready, but you'd likely to want to wait
//for images to load in case they reflow the page
$('body').delay(5000) //wait 5 seconds
.animate({
//animate jQuery's custom "scrollTop" style
//grab the value as the offset of #second from the top of the page
'scrollTop': $('#second').offset().top
}, 300); //animate over 300ms, change this to however long you want it to animate for
});
回答by Mostafa Shahverdy
Use this at the end of your codes
在代码末尾使用它
setTimeout(function(){window.location.hash = '#second';},5000);
Notethat those height:100%;
are wrong.
请注意,那些height:100%;
是错误的。
回答by David L
You could use
你可以用
window.location.hash = '#second';
This will set the focus. I'll leave you to put in some work on a timer solution.
这将设置焦点。我会让你在计时器解决方案上做一些工作。
Also, I would discourage any forcing of the user to focus on a particular div. This is not a very good UX practice and can lead to chasing users off your site, especially because they may not understand why the page is scrolling up.
此外,我不鼓励任何强迫用户专注于特定 div 的行为。这不是一个很好的 UX 实践,可能会导致用户离开您的网站,尤其是因为他们可能不明白为什么页面向上滚动。
回答by TiagoBrenck
$(function () {
setTimeout(function () { goToSecondTab(); }, 5000);
function goToSecondTab() {
window.location.hash = '#second';
}
});
回答by Arroyo
Add HTML to this line in zzzzBov's script to make it work properly in FF:
将 HTML 添加到 zzzzBov 脚本中的这一行,使其在 FF 中正常工作:
$('html, body').delay(5000) //wait 5 seconds