所以我正在尝试制作一个小小的“Matrix”主题程序,我希望用户输入他们的名字,然后程序将每秒运行20个数字,因为它每1秒显示一个名字的每个字符,从左到右。我究竟做错了什么?目前为止所有工作都是数字滚动
<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>
答案 0 :(得分:2)
setInterval是循环,你不需要额外的for循环。此外,您应该设置变量以存储设置间隔的返回值,以便稍后在您希望它停止运行时清除它。
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/
答案 1 :(得分: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);
}