2011-06-18 37 views
0

所以我想制作一个“矩阵”主题程序,我希望用户输入他们的名字,然后程序每秒钟运行20个数字,因为它显示每个字符他们的名字每1秒,从左到右。我究竟做错了什么?到目前为止,所有工作都是滚动的数字在其他内容之前使用Javascript添加内容

<html> 
<head> 
    <script type="text/javascript"> 
    var name = prompt("Enter Your Name to be 'MatrixIzed!':", ""); 

    function numberScroll(){ 
     for (i=0;i<name.length;i++){ 

      setInterval(function() { 
        var n = Math.floor(Math.random() * 9); 
        document.getElementById('txt2').innerHTML = n; 
       }, 50); 

      setInterval(function() { 
        document.getElementById('txt1').innerHTML = name.charAt(i); 
       },1000); 
     } 
    } 
    </script> 
</head> 
<body onLoad="numberScroll()"> 
    <div style="float:left" id="txt1"></div> 
    <div id="txt2"></div> 
</body> 
</html> 

回答

2

setInterval是循环,你不需要额外的循环。此外,你应该设置变量来存储设置的时间间隔的返回值,以便以后可以在需要停止运行时清除它。

function numberScroll(){ 

    // no need to loop i, just set it and increment it in the interval 
    var i = 0; 

    // store interval as variable, so you can stop it later 
    var numbers = setInterval(function(){ 
     var n = Math.floor(Math.random() * 9); 
     document.getElementById('txt2').innerHTML = n; 
    }, 50); 

    var letters = setInterval(function(){ 
     // `+=` rather than `=` to incrementally add to the div's inner html 
     // use and increment i in one step with `i++` 
     document.getElementById('txt1').innerHTML += name.charAt(i++); 
     // when it has reached the end of the name, clear the intervals and empty the second div 
     if(i >= name.length){ 
      clearInterval(numbers); 
      clearInterval(letters); 
      document.getElementById('txt2').innerHTML = ''; 
     } 
    },500); 

} 

小提琴(演示)在这里:http://jsfiddle.net/jW8hZ/

+0

太感谢你了:)我拉我的头发! – bruchowski

+0

不用担心,我可能有时候会使用这个:) –

0

您需要遍历setInterval中的所有字母。

function numberScroll(){ 
    setInterval(function() { 
    var n = Math.floor(Math.random() * 9); 
    document.getElementById('txt2').innerHTML = n;} 
    , 50); 


    var i=0; 
    setInterval(function() { 
    document.getElementById('txt1').innerHTML = name.charAt(i); 
    i = (i+1)%name.lenghth; 
    } 
    ,1000); 

}