条件思路:点击按钮后给以下所有li同时添加背景随即色。
提示:可以通过rgb(随机数, 随机数, 随机数)来实现随机颜色.随机数的取值是0-255,整数.
直接上代码。
<body>
<button>给5个li分别取5种随机背景色</button>
<ul>
<li>111</li>
<li>111</li>
<li>111</li>
<li>111</li>
<li>111</li>
</ul>
<script>
const aLi = document.querySelectorAll('li');
const aBtn = document.querySelectorAll('button')[0];
aBtn.onclick = function(){
for(let i = 0; i < aLi.length; i++){
let num1 = getRand(0, 255);
let num2 = getRand(0, 255);
let num3 = getRand(0, 255);
aLi[i].style.backgroundColor = `rgb(${r},${g},${b})`;
}
// aLi[0].style.backgroundColor = `rgb(${num3},${num2},${num1})`;
// aLi[1].style.backgroundColor = `rgb(${num3},${num3},${num3})`;
// aLi[2].style.backgroundColor = `rgb(${num3},${num1},${num1})`;
// aLi[3].style.backgroundColor = `rgb(${num2},${num2},${num1})`;
// aLi[4].style.backgroundColor = `rgb(${num1},${num2},${num3})`;
}
function getRand(a, b){
return Math.floor(Math.random() * (b - a) + 1) + a
}
</script>
</body>
执行结果: