<!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>
div {
width: 200px;
height: 200px;
background-color: #ccc;
text-align: center;
position: relative;
overflow: hidden;
}
div p {
width: 100px;
height: 20px;
background-color: #fff;
margin: 20px auto;
}
</style>
</head>
<body>
<div>
<p></p>
<p></p>
<button>开始抽奖</button>
</div>
<script>
var arr = ["宝马", "玛莎拉蒂", "兰博基尼", "法拉利", "奥迪", "红旗", "大众", ];
var op = document.getElementsByTagName("p");
var bnt = document.getElementsByTagName("button")[0];
console.log(op, bnt, arr);
//点击按钮 开始随机抽取arr
var timer = null;
var off = 0;
//bnt点击 op的抽奖内容的随机抽取
bnt.onclick = function () {
//点击按钮改变 按钮的值,再点击变回来。
if (off == 0) {
bnt.innerHTML = "点击结束";
auto()
off = 1;
} else {
bnt.innerHTML = "开始抽奖";
off = 0;
clearInterval(timer);
}
}
//对于随机数据 先设置一个 间隔定时器,再设置一个循环得到所有的op的下标,能同重复对同元素使用
function auto() {
timer = setInterval(function () {
//for则给每个p的数组获取对应的下标 op.length 有重复的相同的类型
for (var i = 0; i < op.length; i++) {
// console.log(i)
//数学的 向下选取整数 {数学的随机选择 *最大值-最小值+1 )+1 ----}
op[i].innerHTML = arr[Math.floor((Math.random() * (arr.length - 1 - 0 + 1) + 0))];
}
}, 60)
}
</script>
</body>
</html>