需求:
这里样式不做过多的时间布置,只讲js原理
Math.random() 生成一个0~1的随机数,包括0,不包括1 (小数,而且小数点后有好几位,不信不log试试)
Math.floor() 向下取整数
Math.floor(Math.random()) 去除小数点后面的小数,而取整
Math.floor(Math.random() * arr.length ) arr.length为6,生成一个[0~6)的随机数,左闭右开 取不到6,正好取到5 [0,1,2,3,4,5] 正好是数组的索引值
let random = Math.floor(Math.random() * arr.length)
<!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>随机点名</title>
</head>
<body>
<h1 class="h1">这里显示姓名</h1>
<button id="btn1">开始</button>
<button id="btn2">结束</button>
<script>
// 1. 获取元素
let h1 = document.querySelector('.h1')
let btn1 = document.querySelector('#btn1')
let btn2 = document.querySelector('#btn2')
let arr = ['张三', '李四', '王五', '张六', '小七', '王八']
// 2. 生成随机数
// Math.random() 生成一个0~1的随机数,包括0,不包括1 (小数,而且小数点后有好几位,不信不log试试)
// Math.floor() 向下取整数
// Math.floor(Math.random()) 去除小数点后面的小数,而取整
// Math.floor(Math.random() * arr.length ) arr.length为6,生成一个[0~6)的随机数,左闭右开 取不到6,正好取到5 [0,1,2,3,4,5] 正好是数组的索引值
// let random = Math.floor(Math.random() * arr.length)
// console.log(random)
// 3. 全局声明一个定时器为了清除定时器
let timer = null
// 4. 注册点击事件开启定时器和关闭定时器
btn1.onclick = function () {
timer = setInterval(() => {
h1.innerHTML = arr[Math.floor(Math.random() * arr.length)]
}, 100);
}
btn2.addEventListener('click', function () {
clearInterval(timer)
})
</script>
</body>
</html>