我尝试编写一段代码,在屏幕上显示随机文本并有时更改颜色(在循环 2 中)。
我不明白为什么我的代码只循环一次。看来 show() 函数本身可以工作,但 test() 循环运行得不好。
<script type="text/javascript">//<![CDATA[
window.onload=function(){
button.addEventListener('mousedown', function (e) {
test();
});
}//]]>
function show() {
b=makeid();
document.getElementById("text").innerHTML = b;
}
function test() {
var div = document.getElementById('text');
for (i=0;i<5;i++) {b=makeid();
document.getElementById("text").innerHTML = b;
if (i==2) {div.style.color = '#000000';}
setTimeout(function(){ show();},500);
if (i==2) {div.style.color = '#CC0000';}
}
}
function makeid() {
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for( var i=0; i < 2; i++ )
text += possible.charAt(Math.floor(Math.random() * possible.length));
return text;
}
</script>
</head>
<body>
<button id="button">click</button>
<div>
<span id="text"></span>
</div>
</body>
最佳答案
Your Code is not sufficient for what you are trying to achieve
您的代码存在问题:-
您使用固定超时调用 show()
函数,因此即使该函数等待,它的所有实例也会在同一时间段后立即调用。
而且您无法用眼睛看到文本的变化。
如果是颜色:- 您总是将颜色更改为相同的颜色,因此输出中始终是单色。
我已经达到了你的要求。试试这个:-
<script type="text/javascript">
window.onload=function(){
button.addEventListener('mousedown', function (e) {
test();
});
}
function show()
{
b=makeid();
document.getElementById("text").innerHTML = b;
}
function test()
{
var div = document.getElementById('text');
var repeat = setInterval(function(){
div.style.color = getRandomColor();
show();
},500);
setTimeout(function(){clearInterval(repeat);},2500);
}
function getRandomColor() {
var letters = '0123456789ABCDEF';
var color = '#';
for (var i = 0; i < 6; i++ ) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
function makeid()
{
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for( var i=0; i < 2; i++ )
text += possible.charAt(Math.floor(Math.random() * possible.length));
return text;
}
</script>
</head>
<body>
<button id="button">click</button>
<div>
<span id="text"></span>
</div>
</body>
关于javascript - 随机更改文本和颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44429675/