设计好框架,这里就随便设计一个简单的框架
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>随机点名</title>
<style>
.random_qust{
margin: 50px auto;
text-align: center;
width: 500px;
height: 250px;
background-color: pink;
border:1px solid transparent
}
h2{
margin-top: 30px;
margin-bottom: 50px;
}
.button{
display: flex;
justify-content: space-around;
}
</style>
</head>
<body>
<div class="random_qust">
<h2>随机回答</h2>
<h3>问题是:现在阶段来说:函数中的this指向谁</h3>
<div class="button">
<button class="sure">确定</button>
<button class="end">结束</button>
</div>
</div>
</body>
</html>
在Javascript中定义变量与对象
let question = ['赵云','刘备','关羽','马超','张飞']
let random //随机数
let time
const button_sure = document.querySelector('.sure') //确定按钮
const button_end = document.querySelector('.end') //结束按钮
const content = document.querySelector('.random_qust h3') //显示的内容(名字)
当点击确定按钮时,利用随机数对数据进行索引,并将其显示出来,每100ms随机显示一次;
当点击结束按钮时,停止即可。
代码如下:
button_sure.addEventListener('click',function () {
time = setInterval(function () {
random = parseInt(Math.random()*question.length)
content.innerHTML = question[random]
},100)
})
button_end.addEventListener('click',function () {
content.innerHTML = question[random]
clearInterval(time)
})
结果如下: