javascript x 秒后显示一个 div,y 秒后显示另一个 div

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18808383/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 13:18:14  来源:igfitidea点击:

Reveal a div after x seconds, and reveal another div after y seconds

javascripthtml

提问by N00B

I am very new to this, but I'm attempting to reveal div1 after 1 second, and reveal div2 after 5 seconds. At the moment, only div2 is displaying after 1 second. Please help me fix the javascript.

我对此很陌生,但我试图在 1 秒后显示 div1,并在 5 秒后显示 div2。目前,只有 div2 在 1 秒后显示。请帮我修复javascript。

I'd also like to know how to hide div1 after div2 is displayed.

我还想知道如何在显示 div2 后隐藏 div1。

My code:

我的代码:

<div id="div1" style="visibility: hidden">Reveal Div 1 after 1 second</div>
<div id="div2" style="visibility: hidden">Reveal Div 2 after 5 seconds</div>

<script type="text/javascript">
function showIt() {
  document.getElementById("div1").style.visibility = "visible";
}
setTimeout("showIt()", 1000); // after 1 sec

function showIt() {
  document.getElementById("div2").style.visibility = "visible";
}
setTimeout("showIt()", 5000); // after 5 secs
</script>

回答by Yuriy Galanter

You cannot have 2 function with the same name. Change second part to

不能有 2 个同名的函数。将第二部分更改为

function showIt2() {
  document.getElementById("div2").style.visibility = "visible";
}
setTimeout("showIt2()", 5000); // after 5 secs

Demo: http://jsfiddle.net/W9YU5/

演示:http: //jsfiddle.net/W9YU5/

回答by j08691

Two problems.

两个问题。

  1. Each function must have a distinct name.
  2. You call a function in setTimeout like setTimeout(showIt, 5000); // after 5 secs
  1. 每个函数必须有一个不同的名称。
  2. 您在 setTimeout 中调用一个函数,例如 setTimeout(showIt, 5000); // after 5 secs

jsFiddle example

jsFiddle 示例