用js写隔行变色且颜色随机
话不多说先上效果图
HTML代码:
css:
#threebox {
width: 600px;
border: 1px solid greenyellow;
margin: 0 auto;
}
html:
<p>3、隔行变色</p>
<div id="threebox">
<input type="button" value="变" onclick="bian()">
<ul id="threeOli">
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
</div>
javascript代码:
let threeOli = document.getElementById("threeOli").children;
var threecolor;
function bian() {
for (let j = 0; j < 6; j++){ //循环6次生成6位颜色值
if(j%6==0){ //如果颜色值是6位让其加上#号进行下面的代码
threecolor="#";
}
threecolor += Math.floor(Math.random()*16).toString(16);//产生随机颜色
}
for (let i = 0; i < threeOli.length; i++){
if (i % 2 == 0) {
threeOli[i].style.backgroundColor = threecolor;//偶数行进行颜色赋值
}else {
threeOli[i].style.backgroundColor = "";
}
}
}