<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
* {
margin: 0;
padding: 0;
list-style: none;
text-decoration: none;
}
.luckyDraw {
width: 420px;
margin: 0 auto;
}
.prize {
font-size: 30px;
}
.lottery {
width: 240px;
margin: 80px auto;
position: relative;
}
.lottery li {
width: 80px;
height: 80px;
border: 1px solid #000;
box-sizing: border-box;
text-align: center;
line-height: 80px;
position: absolute;
}
.lottery li:nth-of-type(1) {
left: 0;
top: 0;
}
.lottery li:nth-of-type(2) {
left: 80px;
top: 0;
}
.lottery li:nth-of-type(3) {
left: 160px;
top: 0;
}
.lottery li:nth-of-type(4) {
left: 160px;
top: 80px;
}
.lottery li:nth-of-type(5) {
left: 160px;
top: 160px;
}
.lottery li:nth-of-type(6) {
left: 80px;
top: 160px;
}
.lottery li:nth-of-type(7) {
left: 0;
top: 160px;
}
.lottery li:nth-of-type(8) {
left: 0;
top: 80px;
}
.lottery li:nth-of-type(9) {
left: 80px;
top: 80px;
cursor: pointer;
background: gold;
}
.active:after {
position: absolute;
top: 0;
left: 0;
content: "";
width: 100%;
height: 100%;
background: rgba(0, 0, 0, 0.1);
}
</style>
</head>
<body>
<div class="luckyDraw">
<ul class="lottery">
<li class="active">1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
<li>6</li>
<li>7</li>
<li>8</li>
<li>点击抽奖</li>
</ul>
<span class="prize">奖品</span>
</div>
<script type="text/javascript">
var arr = [1, 2, 3, 4, 5, 6, 7, 8]; //奖品
var lottery = document.querySelector(".lottery");
var prize = document.querySelector(".prize");
var ali = lottery.querySelectorAll("li");
console.log(ali)
var i = 0; //当前转到哪个位置
var count = 0; //转圈初始值
var totalCount = 9; //转动的总圈数
var index = 1; //默认中奖位置
var speed = 500; //旋转速度初始值
var minSpeed = 500; //旋转最小速度
var timer; //定时器
var isClick = true;
function roll() {
speed -= 50;
if(speed <= 10) {
speed = 10
}
var child = ali[i].parentNode.children;
for(var j = 0; j < child.length; j++) {
child[j].classList.remove("active");
}
i++;
if(i >= ali.length - 1) {
i = 0;
count++;
}
prize.innerHTML = arr[i];
ali[i].classList.toggle("active");
if(count >= totalCount && i == index - 1) {
clearTimeout(timer);
isClick = true;
speed = minSpeed;
console.log(isClick, speed)
} else {
if(count >= totalCount - 1 || speed <= 50) {
speed += 100
}
//计时器不能放到判断外面,否则无法清除该计时器
timer = setTimeout(roll, speed);
}
}
ali[ali.length - 1].onclick = function() {
if(isClick) {
count = 0;
index = Math.floor(Math.random() * arr.length + 1);
console.log(index)
//随机产生中奖位置
console.log("中奖位置:" + index);
roll();
isClick = false;
}
}
</script>
</body>
</html>
网友评论