<!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>
</head>
<style>
div {
height: 200px;
width: 500px;
background-color: black;
margin: 50px auto;
color: aliceblue;
}
button {
background-color: aquamarine;
}
p {
height: 100px;
width: 300px;
background-color: skyblue;
margin: auto;
margin-top: 25px;
text-align: center;
line-height: 100px;
font-size: 20px;
}
</style>
<body>
<div>
<button>开始</button>
<button>停止</button>
<p></p>
</div>
<script>
var arr = ['上三', '钢弹', '狗子', '老六', '小气', '王五'];
var btn1 = document.querySelectorAll('button')[0];
var btn2 = document.querySelectorAll('button')[1];
var p = document.querySelector('p');
// 点击开始
btn1.addEventListener('click', function () {
// 每5秒在数组内随机选择
var time = setInterval(fn, 50);
// fn函数
function fn() {
var random = Math.round(Math.random() * (arr.length - 1) + 0);
p.innerHTML = arr[random];
}
btn2.addEventListener('click', function () {
clearInterval(time);
})
})
</script>
</body>
</html>