<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>无标题文档</title>
<style>
.gift{
background-color:#FFF;
display:inline-table;
width:100px;
height:100px;
text-align:center;
padding:40px;
}
</style>
</head>
<body>
<div>
<div class="gift gift1">1</div>
<div class="gift gift2">2</div>
<div class="gift gift3">3</div>
</div>
<div>
<div class="gift gift0">8</div>
<div style="display:inline-table;"><button style="width:100px; height:100px;">ooo</button></div>
<div class="gift gift4">4</div>
</div>
<div>
<div class="gift gift7">7</div>
<div class="gift gift6">6</div>
<div class="gift gift5">5</div>
</div>
<span style="color:#ff0000;"><script src="jquery-1.11.2.js"></script></span>
<script type="text/javascript">
$(function(e) {
var stopStep=1;//表示最终奖品位置
var runT=null;//转动方法
var step=-1;//计算转动的步数,控制转速和停止
var during=2;//转速
$("button").click(function(e){
stopStep=Math.floor(Math.random()*8+1);
runT=setTimeout(runF,100);
});
function runF(){
if(step>=(32+stopStep))//设置转动多少圈
{
$(".gift"+(step%8)).css("background-color","#F00");
step=stopStep;
alert("you get"+step);
clearTimeout(runT);//停止转动
return;
}
if(step>=(24+stopStep)){ //在即将结束转动前减速
during+=1;
}else{
if(during<=2){ //控制中间转速
during=2;
}
during--;
}
step++;
$(".gift").each(function(index, element) {
$(this).css("background-color","#FFF");
});
$(".gift"+(step%8)).css("background-color","#F00");
runT=setTimeout(runF,during*50);
}
});
</script>
</body>
</html>
最近学了js,练练手。
注意需要添加jquery,以上代码主要实现基本九宫格抽奖模型,界面内容自己完善。
思路:九宫格抽奖抽象出来,其实就是点击抽奖按钮以后,从某个单元开始,不停的绕着8个格子转动,最后停留在目标位置。
也就是说,一开始就可以设定好目标位置stopStep,并用一个变量step用于计算转动的步数,这个计算的变量从0或1开始计算,直到达到设置的转动次数(就是你要他转多少圈)*8+stopStep,在这个转动的过程,你可以设置不同的转速。在转动过程中,要不断改变当前位置的单元格的颜色(或者你设置其他表示被选中的样式),每次还要记得先把上一步改变了颜色的单元格恢复到原来的样式。基本这样!