Javascript - 试着让它等待

use*_*419 0 html javascript

好的,所以我试图让这段代码在特定的div中以不同的间隔显示文本."text1"通常出现在div中,但几秒后页面加载的所有内容都会消失,文本在空白页面上可见.

有人可以帮助我,所以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>
Run Code Online (Sandbox Code Playgroud)

med*_*iev 5

那是因为你正在使用document.write.它重写整个文档.使用方法类似appendChild或者replaceChild甚至是.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>
Run Code Online (Sandbox Code Playgroud)

编辑#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>
Run Code Online (Sandbox Code Playgroud)