DEMO:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
*{margin: 0;padding: 0;}
ul{
overflow: hidden;
margin: 100px;
width: 270px;
padding: 4px;
border: 1px solid #ccc;
}
ul li{
list-style: none;
float: left;
width: 80px;
height: 80px;
border: 1px solid #ccc;
margin: 4px;
text-align: center;
line-height: 80px;
font-size: 32px;
}
.disabled{
background-color: #ccc;
cursor: not-allowed;
}
.active{
background-color: yellow;
color: #fff;
}
.btn{
cursor: pointer;
border-radius: 50%;
}
</style>
</head>
<body>
<div>
<ul>
<li class="prize1">奖1</li>
<li class="prize2">奖2</li>
<li class="prize3">奖3</li>
<li class="prize8">奖8</li>
<li class="btn" id="btn">开始</li>
<li class="prize4">奖4</li>
<li class="prize7">奖7</li>
<li class="prize6">奖6</li>
<li class="prize5">奖5</li>
</ul>
</div>
</body>
<script type="text/javascript">
window.onload = function(){
Fun.init();
var _curInd = Fun.curInd;//保存初始位置,方便重置
var oBtn = document.querySelector('#btn');
oBtn.onclick = function(){
if(!oBtn.classList.contains('disabled')){
Fun.revert(_curInd);
oBtn.classList.add('disabled');
// 运动
Fun.move();
}
}
}
var Fun = {
curInd: 3,//当前位置
config: {
prizeArr: [1, 3, 5, 7],//只能获取奖品1,3,5,7
speed: 40,//初始转动速度 40ms
cycle: 40,//最少转动 40次
changeSpeed: 24,//转动24次后开始放缓速度
},
rnd: function(min, max){//[min, max]
return Math.floor(Math.random()*(max-min+1) + min);
},
init: function(){
let oActive = document.querySelector('.active');
if(oActive){
oActive.classList.remove('active');
}
document.querySelector('.prize'+this.curInd).classList.add('active');
},
move: function(){
var _this = this;
// 获取奖品位置
var prizeInd = _this.config.prizeArr[_this.rnd(0, _this.config.prizeArr.length-1)];
var times = 0;//已经转了多少次
var t = _this.config.speed;
var timer = setInterval(fn, t);
function fn(){
if (times >= _this.config.cycle && _this.curInd == prizeInd) {
// 转动次数达到要求,且已到达中奖位置
console.log('转动了' + times + '次获得:', document.querySelector('.active').innerHTML);
document.querySelector('#btn').classList.remove('disabled');
clearInterval(timer);
}else{
if (times >= _this.config.changeSpeed) {
if (((prizeInd == 1 && _this.curInd == 8) || prizeInd == (_this.curInd+1)) &&
times >= _this.config.cycle
) {// 最后一下
console.log('last time');
t += 300;
}else{
// console.log('开始减速');
t += 10;
}
// 注意:想要改变定时器时间只能关了再开,直接修改是没用的
clearInterval(timer);
timer = setInterval(fn, t);
}
document.querySelector('.active').classList.remove('active');
_this.curInd = _this.curInd + 1 > 8 ? 1 : (_this.curInd + 1);
document.querySelector('.prize'+_this.curInd).classList.add('active');
times ++;
}
};
},
// 还原
revert: function(curInd){
this.curInd = curInd;
this.init();
}
}
</script>
</html>
网友评论