<!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: 30px 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");
var i=0; //当前转到哪个位置
var count = 0; //转圈数初始值
var totalCount = 9; //转动的总圈数
var index = 1; //默认中奖位置
var speed = 500;//旋转速度初始值
var minSpeed = 500;//旋转最小速度
var timer; //定时器
var isClick = true;
//前两次只能中2
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++;
// console.log(i);
if(i>=ali.length-1){//8
i=0;
count++;
}
prize.innerHTML = arr[i];
ali[i].classList.toggle("active");
// 当转到第九圈的时候就停止,随机数index是[1,8],i是[0,8],随意随机数需要index-1,清除计时器
if(count>=totalCount&&i==index-1){ //if(count==totalCount&&i==index)
clearTimeout(timer);
isClick=true;
speed=minSpeed;
// console.log(count);
}else{//这个else是啥意思
//转的圈数等于8和9的时候就是最后两圈,或者speed<=50开始减速
if(count>=totalCount-1||speed<=50){
speed+=100//减速
}
//计时器不能放到判断外面,
timer = setTimeout(roll,speed);//调用自己
}
}
console.log(ali.length)//9
var onclicktime =0;
ali[ali.length-1].onclick = function(){
//前两次只能中2
if(onclicktime<2&&isClick){//前两次只能中2
count=0;
index = 2;// 中奖位置
console.log("中奖位置:"+index);
isClick=false;
roll();
onclicktime+=1;
console.log(onclicktime)
}
else if(onclicktime>=2&&isClick){
count=0;
index = Math.floor(Math.random()*arr.length+1);//中奖位置
// Math.floor((Math.random()*8)+1);//[1,8]
//随机产生中奖位置
// index = 1;设置中第几个
console.log("中奖位置:"+index);
isClick=false;
roll();
}
}
</script>
</body>
</html>
网友评论