点击「开始闪」后,三个随机的不同方块颜色变为三种随机的颜色。
点击「结束闪」后,停止方块闪动。
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
.box {
width: 100%;
}
.cell {
float: left;
margin: 1.5%;
padding: 15%;
background-color: #ffa600;
border-radius: 10%;
}
.clear {
clear: both;
}
.btn1,
.btn2 {
width: 100%;
height: 10%;
padding: 5% 0;
margin-top: 5%;
background-color: white;
border: 2px solid #ffa600;
border-radius: 10px;
outline: none;
}
.btn1:hover,
.btn2:hover {
background-color: #ffa600;
}
.btn1:active,
.btn2:active {
background-color: #ffa600;
}
</style>
<script src="index.js"></script>
</head>
<body>
<div class="box">
<div class="cell"></div>
<div class="cell"></div>
<div class="cell"></div>
<div class="cell"></div>
<div class="cell"></div>
<div class="cell"></div>
<div class="cell"></div>
<div class="cell"></div>
<div class="cell"></div>
<div class="clear"></div>
<input type="button" class="btn1" value="开始闪" />
<input type="button" class="btn2" value="结束闪" />
</div>
</body>
</html>
index.js
// 随机出三个格子的下标
function getRandomInt() {
let array = []
// 只需要 3 个不同的数字来取格子
while (array.length < 3) {
let a = Math.floor(Math.random() * cells.length)
// 防止随机数重复
if (!array.includes(a)) {
array.push(a)
}
}
console.log(array)
return array
}
// 随机颜色
function getColor() {
var r = Math.floor(Math.random() * 255)
var g = Math.floor(Math.random() * 255)
var b = Math.floor(Math.random() * 255)
var colorStr = `rgb(${r}, ${g}, ${b})`
return colorStr
}
// 开始闪
function changeColor() {
let nums = getRandomInt()
reColor()
for (let i = 0; i < nums.length; i++) {
let color = getColor()
cells[nums[i]].style.setProperty(‘background-color‘, color)
}
}
// 恢复一开始的颜色
function reColor() {
for (let i = 0; i < cells.length; i++) {
cells[i].style.setProperty(‘background-color‘, ‘#ffa600‘)
}
}
// 结束闪
function endChange() {
clearInterval(timer)
reColor()
}
var cells = document.getElementsByClassName(‘cell‘)
var timer = null
window.onload = function () {
var btn1 = document.querySelector(‘.btn1‘)
var btn2 = document.querySelector(‘.btn2‘)
btn1.addEventListener(‘click‘, function () {
timer = setInterval(changeColor, 700)
})
btn2.addEventListener(‘click‘, endChange)
}
我觉得取到相同颜色的概率极低,所以就没判断颜色相不相等了~
原文:https://www.cnblogs.com/gullrye/p/13721454.html