简易的点击按钮隔行变色
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style>
/*css的样式*/
div{width: 250px;height: 45px;margin-bottom: 4px;box-shadow: 0 2px 4px #CCCCCC;border-radius: 2px;}
#box{width: 250px;margin: 0 auto;height: 350px;text-align: center;}
.bnt{width: 90px;font: 16px/25px "";display: block;border-radius: 12px;margin: 20px auto 0; }
</style>
</head>
<body>
<!--布局-->
<div id="box">
<div>hello</div>
<div>hello</div>
<div>hello</div>
<div>hello</div>
<div>hello</div>
<div>hello</div>
<input type="button" value="隔行换色" class="bnt"/>
</div>
</body>
<script>
//先获取div和button
var obox=document.querySelector("#box");
var obtn=document.querySelector(".bnt");
//获取div所有子元素
var arr=obox.children;
var box=document.querySelector("#a1");
//随机颜色的封装
function random(n,m){
return Math.round(Math.random()*(n-m)+m);
}
function randomcolor(){
var a=random(0,255).toString(16);
var b=random(0,255).toString(16);
var c=random(0,255).toString(16);
return "#"+bu(a)+bu(b)+bu(c);
}
//补零
function bu(a){
if(a.length<2){
return "0"+a;
}else{
return a;
}
}
//i用来记录状态
var i=0;
obtn.onclick=function(){
if(i==0){
for(var j=0;j<arr.length-1;j++){
if((j+1)%2==0){
arr[j].style.backgroundColor=randomcolor();
}else{
arr[j].style.backgroundColor="#fff";
}
}
i=1;
}else{
for(var j=0;j<arr.length-1;j++){
if((j+1)%2==0){
arr[j].style.backgroundColor="#fff"
}else{
arr[j].style.backgroundColor=randomcolor();
}
}i=0;
}
}
</script>
</html>