彩虹灯
- HTML
<body>
<div class="secWrap">
<div class="fir">
<div class="sec">
<div class="thr">
<div class="four"></div>
</div>
</div>
</div>
</div>
<div class="secBtns">
<button id="outToIn">从外到里</button>
<button id="inToOut">从里到外</button>
</div>
<img src="./img/1.gif" id="ligthImg" alt="">
<div class="doubleColorWrap">
<p id="dcText"></p>
<button id="dcBtn">随机一注</button>
</div>
</body>
- CSS
.fir {
width: 500px;
height: 500px;
border: 1px solid red;
margin: auto;
background-color: #ffffff;
}
.sec {
width: 400px;
height: 400px;
border: 1px solid red;
margin: 49px auto 0;
background-color: #ffffff;
}
.thr {
width: 300px;
height: 300px;
border: 1px solid red;
margin: 49px auto 0;
background-color: #ffffff;
}
.four {
width: 200px;
height: 200px;
border: 1px solid red;
margin: 49px auto 0;
background-color: #ffffff;
}
.secBtns {
margin-top: 20px;
text-align: center;
word-spacing: 40px;
}
- JS
<!-- 导入自己封装的js文件 -->
<script src="./js/tool.js"></script>
<script>
/**
* 获取页面元素
*/
var outToIn = document.getElementById('outToIn');
var inToOut = document.getElementById('inToOut');
var divs = document.querySelectorAll('.secWrap div');
// 从外到里
var outToInTimer;
outToIn.onclick = function() {
// 清除老的计时器
clearInterval(outToInTimer);
clearInterval(inToOutTimer);
// 生成新的计时器
outToInTimer = setInterval(function() {
for (var i = 3; i > 0; i--) {
divs[i].style.backgroundColor = divs[i - 1].style.backgroundColor;
}
// 0 随机 颜色
divs[0].style.backgroundColor = randomColor();
}, 1000);
}
// 从里向外
var inToOutTimer;
inToOut.onclick = function() {
// 清除老的计时器
clearInterval(inToOutTimer);
clearInterval(outToInTimer);
// 生成新的计时器
inToOutTimer = setInterval(function() {
for (var i = 0; i < 3; i++) {
divs[i].style.backgroundColor = divs[i + 1].style.backgroundColor;
}
// 3 随机颜色
divs[3].style.backgroundColor = randomColor();
}, 1000);
}
tool.js
// 随机颜色
function randomColor() {
var r = randomNum(0, 255);
var g = randomNum(0, 255);
var b = randomNum(0, 255);
return "rgb(" + r + ", " + g + ", " + b + ")";
}
// 随机数
function randomNum(a, b) {
return Math.floor(Math.random() * (b - a + 1) + a);
}
效果: