要求:
开始和停止在一个按钮上
按钮可以重复使用-开始-停止-开始-停止--
做法:
主要是给按钮添加点击事件,使用计数器%2判断当前点击是开始还是停止并相应给出样式内容变换
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<style>
#div1{
width: 150px;
height: 100px;
background-color: orangered;
padding-top: 25px;
}
#demo{
width: 100px;
height: 50px;
background-color: lightgrey;
line-height: 50px;/*行高=高度 垂直居中*/
margin-left: 25px;
font-family: "微软雅黑";
font-weight: bold;
text-align: center;
}
#btn{
margin-left:50px;
}
</style>
<body>
<div id="div1">
<div id="demo">随机点名器</div>
<button type="button" id="btn">开始</button>
</div>
</body>
<script>
var count=0;
var flag1;
function changeName(){
var arr=new Array("唐三","小舞","戴沐白","朱竹清","香肠大叔","胖子","赵无极");
var randomNum=Math.floor(Math.random()*arr.length);
document.getElementById("demo").innerHTML=arr[randomNum];
}
document.getElementById("btn").onclick=function(){
console.log(count);
count++;
if(count%2!=0){
flag1=window.setInterval("changeName()",100);
this.style.backgroundColor="red";
this.innerHTML="开始";
}else{
this.innerHTML="停止";
this.style.backgroundColor="green";
window.clearInterval(flag1);
}
}
</script>
</html>