在很多网站,app中我们都能看见抽奖功能,但是我们都能发现,很难抽中那些比较吸引人的东西,接下来我们来解开抽奖的面纱!
效果图
一,原理
通过,循环给最外层标签添加样式,让后通过匹配两个数组的值是否相等来停止转动,达到抽奖效果!
二,模板展示
// 通过js构建外层dom
function render(){
view.children[0].style.left=0;
view.children[0].style.top=0;
view.children[1].style.left="200px";
view.children[1].style.top=0;
view.children[2].style.left="400px";
view.children[2].style.top=0;
view.children[3].style.left="400px";
view.children[3].style.top="200px";
view.children[4].style.left="400px";
view.children[4].style.top="400px";
view.children[5].style.left="200px";
view.children[5].style.top="400px";
view.children[6].style.left=0;
view.children[6].style.top="400px";
view.children[7].style.left=0;
view.children[7].style.top="200px";
}
render();
三,定义外层抽奖数据列表页面
//展示在页面的抽奖列表
var arr=["土豆丝炒肉","舒雅炒面","减肥餐","不吃饭","尖椒炒鸡蛋","点外卖","喝点粥","吃面条"];
//for循环遍历插值
for(var i=0;i
var node=document.createElement("div");
node.innerHTML=arr[i];
node.index=[i];
view.appendChild(node);
}
四,自定义中奖数据
// 用来随机选中的数组,通过跟页面展示数组对比,来判断抽奖结果,抽奖精华就在这我们能通过这个控制用户能抽到那些东西,省的你的客户赔死。
var allowList=["土豆丝炒肉","尖椒炒鸡蛋","点外卖","喝点粥","吃面条"]
这是抽奖的核心这个数据可以来确定用户能抽到那些奖品,
五,循环改变样式停止奖盘转动
//获取随机数
function random(a,b){
return Math.floor(Math.random()*(b-a+1))+a;
}
view.children[0].className="con";
var count=0;
var flag=true;
begin.οnclick=function(){
var ran=random(0,allowList.length-1);//当点击开始的时候获取一个随机数
console.log(allowList[ran]);
var t=100;//定义初始转动时间
flag=true;//控制转动开关
function fun(){
// 切换类名,改变标签样式
view.children[count].className="";
count++;
if(count>view.children.length-1){
count=0;
}
view.children[count].className="con";
if(flag){
// 减小计时器时间,增大速度
if(t>50){
t-=5;
}else{
flag=false;
}
console.log(t)
}else{
if(t<=500){
t+=30;
}
console.log(t)
}
//z自己修改后所加
// 所到标签内容是否为随机内容
var allowFlag=view.children[count].innerHTML==allowList[ran];
if(t>500&&allowFlag){//停止计时器循环
console.log(view.children[count].innerHTML);
}
else{
setTimeout(fun,t)
}
}
fun()
}
六,样式
*{
margin:0;
padding:0
}
#view{
width:600px;
height: 600px;
position: relative;
margin:50px auto
}
#view div{
width: 200px;
height: 200px;
position: absolute;
background: #dedede;
border-radius: 10px;
line-height: 200px;
text-align: center;
}
#view .con{
background: orange;
color:red;
font-weight: bolder
}
#begin{
width: 200px;
height: 200px;
position: absolute;
background: lightblue!important;
color: #ffffff!important;
border-radius: 10px;
line-height: 200px;
text-align: center;
left: 200px!important;
top: 200px!important;
}