Javascript - 试图让它等待

Javascript - 试图让它等待

问题描述:

好的,所以我试图让这段代码在特定的div中以不同的间隔显示文本。 “div1”通常出现在div中,但几秒后页面加载一切消失,文本可见,但在空白页面上。Javascript - 试图让它等待

有人可以帮我,所以text2和text3出现在div与其余的内容。

谢谢。

<script type="text/javascript"> 
    function typeText1() 
    { 
     document.write('<p style="color:blue;">text1</p>'); 
     setTimeout("typeText2();", 1000); 
    } 
    function typeText2() 
    { 
     document.write('<p style="color:blue;">text2</p>'); 
     setTimeout("typeText3();", 3000); 
    } 
    function typeText3() 
    { 
     document.write('<p style="color:blue;">text3</p>'); 
    } 
    typeText1(); 
    </script> 
+0

不要使用document.write,你应该将HTML附加到所需的位置。 – Robert 2011-01-21 17:24:07

这是因为您正在使用document.write。它重写整个文档。使用方法如appendChildreplaceChild或甚至.innerHTML

为了简洁我就使用innerHTML作为一个例子:

<div id="thing"></div> 

<script> 
(function() { 
var thing = document.getElementById('thing'); 

function typeText1() { thing.innerHTML = '<p>text1</p>'; setTimeout(typeText2, 1000); } 
function typeText2() { thing.innerHTML = '<p>text2</p>'; setTimeout(typeText3, 1000); } 
function typeText3() { thing.innerHTML = '<p>text3</p>'; } 

typeText1(); 

})(); 
</script> 

编辑#2:

<!doctype html> 
<html> 
<head> 
    <title></title> 
    <style type="text/css" media="screen"> 
    * { margin:0; padding:0; } 
.one { color:red; } 
.two { color:blue; } 
.three { color:yellow; } 
    </style> 
</head> 
<body> 

<p id="thing"></p> 

<script> 
(function() { 
var thing = document.getElementById('thing'); 

function typeText1() { thing.innerHTML+= 'text1'; thing.className+= ' one'; setTimeout(typeText2, 1000); } 
function typeText2() { thing.innerHTML+= '<br>text2'; thing.className+= ' two'; setTimeout(typeText3, 1000); } 
function typeText3() { thing.innerHTML+= '<br>text3'; thing.className+= ' three'; } 

typeText1(); 

})(); 
</script> 

</body> 
</html> 
+0

@meder无需每次都重新创建P元素,因为只有P内容发生变化。 – 2011-01-21 17:31:52

+0

我很清楚这一点,并会切实做一些更有效的事情,但是我只是给他提供了嵌入html的想法和示例,当分配给`innerHTML`时... – 2011-01-21 17:34:11

+0

这可行,但我怎样才能改变它不覆盖text1 ,而是写下一行文字? – user377419 2011-01-21 17:49:20

如果你想获得这样的效果,你可能会寻找更好到一个javascript框架,如jQuery。他们为这些事情提供了许多简单的功能。使用jQuery

简单的例子:

$(function() { 
    $("body") 
     .append("<p style='color:blue;'>text1</p>") 
     .delay(1000) 
     .append("<p style='color:blue;'>text2</p>") 
     .delay(1000) 
     .append("<p style='color:blue;'>text3</p>"); 
}); 

如果你不得不这样做,很多时候,这会是更好的建立一个循环。同样,如果你有很多内容需要延迟,那么最好把它放在HTML中,当页面加载时隐藏它,然后用Javascript来显示它。