继续上一篇,这次给抽奖来个加速和减速,代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.lottery-draw-container{
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%,-50%);
width: 300px;
height: 300px;
border: 1px solid #000;
display: flex;
flex-direction: column;
}
.item{
flex-basis: 100px;
display: flex;
justify-content:center;
align-items: center;
border: 1px solid #000;
}
.active{
background-color: red;
}
</style>
</head>
<body>
<div class="lottery-draw-container">
<div style="display: flex;flex:1;">
<div class="item"><span>一等奖</span></div>
<div class="item"><span>二等奖</span></div>
<div class="item"><span>三等奖</span></div>
</div>
<div style="display: flex;flex:1;">
<div class="item"><span>四等奖</span></div>
<span class="item"><span>开始</span></span>
<div class="item"><span>五等奖</span></div>
</div>
<div style="display: flex;flex:1;">
<div class="item"><span>六等奖</span></div>
<div class="item"><span>七等奖</span></div>
<div class="item"><span>八等奖</span></div>
</div>
</div>
<script>
let lottery = {
key:0,//reset中,改变这个数,此数和中几等奖相关
items:document.querySelectorAll("div.item"),
curIndex:0,
speed:400,
timer:null,
needCycles:6,
alreadyCycles:0,
reset:function () {
lottery.stop();
lottery.items.forEach(function (item) {
item.classList.remove("active");
});
lottery.curIndex = 0;
lottery.speed = 400;
lottery.alreadyCycles = 0;
lottery.key = Math.floor(Math.random()*lottery.items.length);
lottery.start();
},
run:function () {
let curItem = lottery.items[lottery.curIndex];
curItem.classList.add("active");
let preItem = null;
//当当前为一等奖时,上一个为八等奖,
if(lottery.curIndex == 0){
preItem = lottery.items[7];
}else{
preItem = lottery.items[lottery.curIndex-1]
}
//第一回点击开始时上一个是没有active类名的
if(preItem.classList.contains("active")){
preItem.classList.remove("active");
}
lottery.curIndex ++;
//转完一圈时要记录上
if(lottery.curIndex == 8){
lottery.alreadyCycles +=1;
lottery.curIndex = 0;
};
lottery.upSpeed();
lottery.downSpeed();
//判断当跑完足够圈数并且跑到相应key时停止。哈哈,其实跑多少圈只是形式,key已经确定了
if(lottery.alreadyCycles == lottery.needCycles && lottery.curIndex == lottery.key){
lottery.stop();
}
},
//加速和后面的减速判断差不多,前几圈加,后几圈减,都是可以设置的。
upSpeed:function () {
if(lottery.speed>100&&lottery.alreadyCycles<2){
lottery.speed -=70;
}
lottery.stop();
lottery.start();
},
downSpeed:function () {
if(lottery.speed<500&&lottery.alreadyCycles>4){
lottery.speed +=70;
}
lottery.stop();
lottery.start();
},
stop:function () {
clearInterval(lottery.timer);
},
start:function () {
lottery.timer = setInterval(lottery.run,lottery.speed)
}
};
document.querySelector("span.item").onclick = function () {
lottery.reset()
};
</script>
</body>
</html>
点击开始知道结束开始应该失效,这点这回没有,之后要加