我目前正在自学 HTML/Javascript,同事提出了一些挑战。
我正在尝试创建将显示 1-99 之间的 3 个随机数的循环。每个显示随机颜色。进行了一些搜索,但无法找到包含我的循环的这四个方面的任何内容。
下面是我到目前为止所要做的。任何想法如何将其转换为循环?
非常感谢 克里斯
<!DOCTYPE html>
<html>
<body>
<center>
<h1>Hello World!</h1>
<h2>10 Random Coloured Numbers</h2>
<p id="no1"></p>
<p id="no2"></p>
<p id="no3"></p>
<script>
document.getElementById("no1","no2","no3").innerHTML =
Math.floor(Math.random() * 101)
document.getElementById("no1","no2","no3").style.color =
'#' + (Math.random() * 0xFFFFFF << 0).toString(16);
</script>
最佳答案
getElementById
只接受一个参数,所以即使你传递三个它也只会关心第一个,所以你应该将代码更改为:
document.getElementById("no1").innerHTML =
Math.floor(Math.random() * 101)
document.getElementById("no1").style.color =
'#' + (Math.random() * 0xFFFFFF << 0).toString(16);
document.getElementById("no2").innerHTML =
Math.floor(Math.random() * 101)
document.getElementById("no2").style.color =
'#' + (Math.random() * 0xFFFFFF << 0).toString(16);
document.getElementById("no3").innerHTML =
Math.floor(Math.random() * 101)
document.getElementById("no3").style.color =
'#' + (Math.random() * 0xFFFFFF << 0).toString(16);
document.getElementById("no1").innerHTML =
Math.floor(Math.random() * 101)
document.getElementById("no1").style.color =
'#' + (Math.random() * 0xFFFFFF << 0).toString(16);
document.getElementById("no2").innerHTML =
Math.floor(Math.random() * 101)
document.getElementById("no2").style.color =
'#' + (Math.random() * 0xFFFFFF << 0).toString(16);
document.getElementById("no3").innerHTML =
Math.floor(Math.random() * 101)
document.getElementById("no3").style.color =
'#' + (Math.random() * 0xFFFFFF << 0).toString(16);
<h1>Hello World!</h1>
<h2>10 Random Coloured Numbers</h2>
<p id="no1"></p>
<p id="no2"></p>
<p id="no3"></p>
也可以在这里找到:https://jsfiddle.net/9vg262w5/
当然会重复你的代码。像这样写,很容易发现除了 id
之外的所有内容都是相同的,因此您可以使用 for
并保存一些代码,如下所示:
for(var i=1; i<=3; i++){
document.getElementById("no"+i).innerHTML =
Math.floor(Math.random() * 101)
document.getElementById("no"+i).style.color =
'#' + (Math.random() * 0xFFFFFF << 0).toString(16);
}
for(var i=1; i<=3; i++){
document.getElementById("no"+i).innerHTML =
Math.floor(Math.random() * 101)
document.getElementById("no"+i).style.color =
'#' + (Math.random() * 0xFFFFFF << 0).toString(16);
}
<h1>Hello World!</h1>
<h2>10 Random Coloured Numbers</h2>
<p id="no1"></p>
<p id="no2"></p>
<p id="no3"></p>
也可以在这里找到:https://jsfiddle.net/9vg262w5/1/
关于javascript - 随机数,随机颜色循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46609082/