<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>颜色随机的方块</title>
<style>
html{
font-size: 10px;
}
*{
padding: 0;
margin: 0;
}
body{
width: 100%;
}
.content{
width: 40rem;
height: 40rem;
margin: 20px auto;
background-color: #e2e2e2;
border-radius: 5px;
}
.box{
height: 100%;
width: 100%;
display: flex;
flex-flow: row wrap;
list-style: none;
justify-content: space-around;
padding: 0.5rem;
box-sizing: border-box;
}
.box>li{
width: 33.3%;
height: 33.3%;
padding: 0.5rem;
box-sizing: border-box;
border-radius: 3px;
text-align: center;
line-height: 15rem;
}
.box>li>div{
width: 100%;
height: 100%;
background-color: yellow;
}
.btn{
width: 40rem;
margin: 0 auto;
}
.btn>div{
height: 2rem;
text-align: center;
width: 20%;
margin: 0.5rem auto;
line-height: 2rem;
background-color: #e6e6e6;
border-radius: 0.5rem;
cursor: pointer;
}
</style>
</head>
<body>
<div class="content">
<ul class="box">
<li><div class="let_style">1</div></li>
<li><div class="let_style">2</div></li>
<li><div class="let_style">3</div></li>
<li><div class="let_style">4</div></li>
<li><div class="let_style">5</div></li>
<li><div class="let_style">6</div></li>
<li><div class="let_style">7</div></li>
<li><div class="let_style">8</div></li>
<li><div class="let_style">9</div></li>
</ul>
<div class="btn">
<div id="run">点击开始</div>
<div id="stop">点击结束</div>
</div>
</div>
<script>
var list = document.getElementsByClassName('let_style');
var run = document.getElementById('run');
var stop = document.getElementById('stop');
var time;
function begin(one,two,three) {
if(one == two || two == three || one == three){
if(one == two){
one = Math.floor(Math.random()*list.length);
}else if(two == three){
two = Math.floor(Math.random()*list.length);
}else if(one == three){
three = Math.floor(Math.random()*list.length);
}
begin(one,two,three);
}else{
list[one].style.backgroundColor = 'rgb'+ colors();
list[two].style.backgroundColor = 'rgb'+ colors();
list[three].style.backgroundColor = 'rgb'+ colors();
}
//console.log()
}
function colors() {
var rgb;
var r = Math.floor(Math.random()*256);
var g = Math.floor(Math.random()*256);
var b = Math.floor(Math.random()*256);
rgb = '('+r+','+g+','+b+')';
return rgb;
}
run.onclick = function(){
clearInterval(time);
time = setInterval(function(){
for(var i = 0; i < list.length; i++){
list[i].style.backgroundColor = '';
}
var one = Math.floor(Math.random()*list.length);
var two = Math.floor(Math.random()*list.length);
var three = Math.floor(Math.random()*list.length);
begin(one,two,three);
},1000);
}
stop.onclick = function(){
clearInterval(time);
for(var i = 0; i < list.length; i++){
list[i].style.backgroundColor = '';
}
}
</script>
</body>