简易的点击按钮隔行变色

简易的点击按钮隔行变色

<!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>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值