X秒后执行JavaScript [英] Executing JavaScript after X seconds
问题描述
我使用< div>和JavaScript构建了一个插页式页面,非常简单,但整洁。
一切正常,但我也想关闭几秒后div(例如10秒)。这里我到目前为止:
- 我有两个div,1和2。
- I有像div 1的CSS设置:display:none; (div 1包含启动画面的内容)
- Div 2是覆盖页面的层,只保留div 1可见。
为了加载div,我有一个类似这样的onload函数:
onload = document.getElementById('div1')。style.display ='block'; document.getElementById('div2')。style.display ='block'
$ p
隐藏div我有一个像这样的onclick函数:
< a href =javascript:void(0)onclick =document.getElementById('div1')。style.display ='none'; document.getElementById('div2')。style.display ='none' >< / A>
如何使用计时器执行onclick函数,以及如何执行?它也必须在JavaScript中。
解决方案我相信你正在寻找 setTimeout 函数。
为了让代码更简洁,定义一个单独的onclick函数在
< script>
块中:
function myClick (){
setTimeout(
function(){
document.getElementById('div1')。style.display ='none';
document.getElementById('div2') .style.display ='none';
},5000);
}
然后从
onclick
$ bonclick =myClick();
I am building a interstitial page, using <div> and JavaScript, really simple script but neat.
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:
- 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.
To load the div's I have a onload function like this:
onload="document.getElementById('div1').style.display='block';document.getElementById('div2').style.display='block'"
To hide the divs I have an onclick function like this:
<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.
I believe you are looking for the setTimeout function.
To make your code a little neater, define a separate function for onclick in a <script>
block:
function myClick() {
setTimeout(
function() {
document.getElementById('div1').style.display='none';
document.getElementById('div2').style.display='none';
}, 5000);
}
then call your function from onclick
onclick="myClick();"
这篇关于X秒后执行JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!