动态闪烁.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script type="text/javascript" src="js/tool.js"></script>
<style type="text/css">
/*==========顶部===============*/
#top{
height: 400px;
}
#top>#box{
height: 400px;
width: 800px;
border: 1px solid #444;
margin: auto;
}
#top>#box>.s-box{
width: 80px;
height: 80px;
float: left;
}
/*=================底部==============*/
#bottom{
text-align: center;
margin-top: 10px;
}
#bottom>button{
width: 100px;
height: 40px;
color: white;
background-color: red;
border: none;
outline: none;
font-size: 20px;
}
</style>
</head>
<body>
<div id="top">
<div id="box">
</div>
</div>
<div id="bottom">
<button onclick="addBox()">添加</button>
<button id="twinkle">闪烁</button>
</div>
<!--============添加=============-->
<script type="text/javascript">
function addBox(){
//创建小格子对应的标签
var sBoxNode = document.createElement('div')
sBoxNode.className = 's-box'
sBoxNode.style.backgroundColor = randomColor(0.4)
//添加小格子
var boxNode = document.getElementById('box')
var allSBoxNodes = boxNode.children
if(allSBoxNodes.length == 50){
boxNode.lastElementChild.remove()
}
boxNode.insertBefore(sBoxNode, boxNode.firstElementChild)
}
</script>
<!--============闪烁=============-->
<script type="text/javascript">
document.getElementById('twinkle').onclick = function(){
var btnContent = this.innerText
if (btnContent == '闪烁'){
this.innerText = '暂停'
//闪烁
timer1 = setInterval(function(){
var allSBoxNodes = document.getElementById('box').children
for (x=0;x<allSBoxNodes.length;x++){
var sBoxNode = allSBoxNodes[x]
sBoxNode.style.backgroundColor = randomColor(0.4)
}
},100)
}else{
this.innerText = '闪烁'
clearInterval(timer1)
}
}
</script>
</body>
</html>
tool.js
function randomColor(alpha=1){
var r = parseInt(Math.random()*255)
var g = parseInt(Math.random()*255)
var b = parseInt(Math.random()*255)
return 'rgba('+r+','+g+','+b+','+alpha+')'
}