點(diǎn)擊添加可以添加方塊,點(diǎn)擊閃爍,每個(gè)方塊可以閃爍各種顏色,并且閃爍按鈕變?yōu)闀和0粹o,點(diǎn)擊暫停則停止閃爍:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style>
#div{
width: 800px;
height: 400px;
border: 1px solid gray;
position: relative;
margin: auto;
overflow: hidden;
}
#button{
position: relative;
margin-left: 600px;
}
#add,#shan{
width: 50px;
height: 20px;
background-color: gray;
border: 2px solid burlywood;
color: white;
}
</style>
</head>
<body>
<div id="div"></div>
<div id="button">
<input id="add" type="button" value="添加">
<input id="shan" type="button" value="閃爍">
</div>
<script>
function changeColor(){
r = parseInt(Math.random()*256);
g = parseInt(Math.random()*256);
b = parseInt(Math.random()*256);
return 'rgb(' + r + ','+ g +','+ b + ')';
}
var input_1 = document.getElementById('add');
var input_2 = document.getElementById('shan');
var divs = document.getElementById('div');
input_1.addEventListener('click',function(){
var div = document.createElement('div');
div.style.display = 'block';
div.style.width = 80 + 'px';
div.style.height = 80 + 'px';
div.style.float = 'left';
console.log(changeColor());
div.style.backgroundColor = changeColor();
divs.appendChild(div);
});
var timerId; //設(shè)為全局變量才不會(huì)因?yàn)槊看吸c(diǎn)擊重新被初始化
input_2.addEventListener('click',function(){
// window.clearInterval(timerId);
// var timerId;
if(input_2.value=='閃爍'){
input_2.value = '暫停';
timerId = window.setInterval(function(){
var divColor = document.querySelectorAll('#div>div');
for(var i = 0;i < divColor.length;i++){
divColor[i].style.backgroundColor = changeColor();
}
},300);
}else{
input_2.value='閃爍';
window.clearInterval(timerId);
}
});
</script>
</body>
</html>

image.png