Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
279 views
in Technique[技术] by (71.8m points)

html - Executing JavaScript after X seconds

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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();"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...