<!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: 0px;
padding: 0px;
list-style: none;
}
div {
width: 320px;
height: 320px;
border: 1px solid red;
margin: 100px auto;
position: relative;
}
div li {
width: 100px;
height: 100px;
background: pink;
position: absolute;
}
li:nth-of-type(1) {
left: 0px;
top: 0px;
}
li:nth-of-type(2) {
left: 110px;
top: 0px;
}
li:nth-of-type(3) {
left: 220px;
top: 0px;
}
li:nth-of-type(4) {
left: 220px;
top: 110px;
}
li:nth-of-type(5) {
left: 220px;
top: 220px;
}
li:nth-of-type(6) {
left: 110px;
top: 220px;
}
li:nth-of-type(7) {
left: 0px;
top: 220px;
}
li:nth-of-type(8) {
left: 0px;
top: 110px;
}
button {
position: absolute;
left: 110px;
top: 110px;
width: 100px;
height: 100px;
border: none;
outline: none;
}
div ul .current {
opacity: 1;
transition: all 1s;
}
</style>
</head>
<body>
<!-- ul的子级只能是li li的父级只能是ul或者ol-->
<div>
<ul id="box">
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
<button id="btn">抽奖</button>
</div>
<script>
var num = -1;
var t = 0;
var timer;
btn.onclick = function () {
clearInterval(timer);
num = -1;
var n = parseInt(Math.random() * box.children.length)
console.log(n)
timer = setInterval(function () {
num++;
if (num > 7) {
num = 0;
t++;
}
console.log(t)
if (t >= 3) {
if (num >= n) {
clearInterval(timer)
t = 0;
setTimeout(function () {
alert(num+1);
}, 200)
}
}
for (var i = 0; i < box.children.length; i++) {
box.children[i].style.opacity = 0.3;
}
box.children[num].style.opacity = 1;
}, 20)
}
</script>
</body>
</html>
alert()会提前执行,为了正常显示我们想要的结果,可以使用setTimeout()函数
setTimeout()函数和setInterval()计时器一样:
setTimeout(函数, 等待的毫秒数)