随机点名原理:
1.新建一个数组,把需要点名的名单放到一个数组里面
2.遍历数组
3.创建一个随机数,作为数组的下标,随机数最大值为数组长度,最小值为零
4.利用计时器,每隔一段时间生成一个随机数
代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
*{
margin: 0;
padding: 0;
}
.box{
width: 500px;
height: 500px;
margin: 0 auto;
background-color: salmon;
}
.box .box1{
width: 100%;
height: 100px;
background-color: seagreen;
display: flex;
justify-content: space-around;
align-items: center;
}
.box .box1 button{
width: 100px;
height: 50px;
background-color: saddlebrown;
font-size: 30px;
text-align: center;
line-height: 50px;
}
.box .mz{
width: 200px;
height: 200px;
margin: 100px auto;
font-size: 50px;
text-align: center;
line-height: 200px;
background-color: blueviolet
}
</style>
</head>
<body>
<div class="box">
<div class="box1">
<button>开始</button>
<button>停止</button>
</div>
<div id="mz" class="mz">张三</div>
</div>
<script>
var arr = ['张三','李四','王二','麻子','小明','小李','校长','大哥','小弟'];
var btn = document.getElementsByTagName("button");
var mz = document.getElementById("mz");
mz.innerHTML = arr[0];
var timer = null;
btn[0].onclick = function(){
timer = setInterval(function(){
var random = Math.round(Math.random() * arr.length);
mz.innerHTML = arr[random];
}, 30)
}
btn[1].onclick = function(){
clearInterval(timer);
}
</script>
</body>
</html>