X 秒后执行 JavaScript
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8252638/
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
Executing JavaScript after X seconds
提问by Paulo Capelo
I am building a interstitial page, using <div> and JavaScript, really simple script but neat.
我正在构建一个插页式页面,使用 <div> 和 JavaScript,非常简单但整洁的脚本。
Everything is working, but I also would like to close the div's after a few seconds (like 10 seconds, for example). Here what I have so far:
一切正常,但我也想在几秒钟后关闭 div(例如 10 秒)。这是我到目前为止所拥有的:
- I have two div's, 1 and 2.
- I have the CSS setup for div 1 like: display: none; (div 1 have the content for the splash screen)
- Div 2 is the layer that will cover the page and leave only div 1 visible.
- 我有两个 div,1 和 2。
- 我有 div 1 的 CSS 设置,例如: display: none; (div 1 包含启动画面的内容)
- Div 2 是将覆盖页面并只留下 div 1 可见的图层。
To load the div's I have a onload function like this:
要加载 div,我有一个像这样的 onload 函数:
onload="document.getElementById('div1').style.display='block';document.getElementById('div2').style.display='block'"
To hide the divs I have an onclick function like this:
为了隐藏 div,我有一个像这样的 onclick 函数:
<a href = "javascript:void(0)" onclick = "document.getElementById('div1').style.display='none';document.getElementById('div2').style.display='none'"></a>
How can I execute the onclick function with a timer, and how can I do it? It also has to be in JavaScript.
如何使用计时器执行 onclick 功能,我该怎么做?它也必须在 JavaScript 中。
回答by Strelok
I believe you are looking for the setTimeoutfunction.
我相信您正在寻找setTimeout函数。
To make your code a little neater, define a separate function for onclick in a <script>
block:
为了使您的代码更简洁,请在<script>
块中为 onclick 定义一个单独的函数:
function myClick() {
setTimeout(
function() {
document.getElementById('div1').style.display='none';
document.getElementById('div2').style.display='none';
}, 5000);
}
then call your function from onclick
然后从 onclick
onclick="myClick();"
回答by Selvakumar Ponnusamy
setTimeout will help you to execute any JavaScript code based on the time you set.
setTimeout 将帮助您根据您设置的时间执行任何 JavaScript 代码。
Syntax
句法
setTimeout(code, millisec, lang)
Usage,
用法,
setTimeout("function1()", 1000);
For more details, see http://www.w3schools.com/jsref/met_win_settimeout.asp
有关更多详细信息,请参阅http://www.w3schools.com/jsref/met_win_settimeout.asp
回答by Dogbert
onclick = "setTimeout(function() { document.getElementById('div1').style.display='none';document.getElementById('div2').style.display='none'}, 1000)"
Change 1000 to the number of milliseconds you want to delay.
将 1000 更改为要延迟的毫秒数。