我想创建一个webPage,其中大多数文本在屏幕上键入,就像该页面是实时向读者键入的。到目前为止,我想出了这段代码,它可以在屏幕上显示单词,但它不是以键入效果的方式显示的。

<html>
<head>
    <title>Murder on the Menu</title>
    <style type="text/css">
        body{
            background-color:#222222;
            margin:0px;
            padding:0px;
        }
        #typed{
            color:red;
            font-size:150%;
            float:left;
        }
        .cursor{
            height:24px;
            width:2px;
            background:lawngreen;
            float:left;
            opacity:0;
            animation:blink 0.75s linear infinite alternate;

        }
        @keyframes blink{
            50% {
                opacity:0;
            }
            100% {
                opacity:1;
            }
        }

    </style>
</head>
<body>
    <div id="typed"></div>
    <div class="cursor"></div>
     <script type="text/javascript">
            var i=0;
            var txt='Murder on the Menu: a production by Brendan Lewis.';
            var speed=500;
            var identifier;
            function addLetter(word){
                document.getElementById(word).innerHTML += txt.charAt(i);
            }
           for(i=0;i<txt.length;i++){
               setInterval(addLetter("typed"),speed);
           }
    </script>
</body>

最佳答案

您的示例中出错的一件事是,对于txt中的每个字母,您都启动了一个新的间隔而没有停止该间隔,这会导致内存泄漏。

实际发生的使txt一次全部可见的事情是,通过将addLetter传递给这样的间隔:setInterval(addLetter("typed"),speed);您实际上在将函数传递到间隔之前就调用了该函数。实际上,txt是按照for loop的速度打印的。

您需要做的是传递一个匿名函数,该函数使用正确的参数调用addLetter,请参见答案。

解:

<script type="text/javascript">
   var i=0;
   var txt='Murder on the Menu: a production by Brendan Lewis.';
   var speed=500;
   var identifier;
   var interval = setInterval(function() {
      return addLetter("typed")
   }, speed);

   function addLetter(word){
     document.getElementById(word).innerHTML += txt.charAt(i);
     if (i < txt.length) i++;
     else clearInterval(interval)
   }

</script>

10-05 20:52
查看更多