Welcome 微信登录

首页 / 脚本样式 / JavaScript / js实现可键盘控制的简单抽奖程序

本文实例为大家分享了js抽奖程序的编写代码,以及编写注意事项,感兴趣的小伙伴们可以参考一下

 
代码:

<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>简单抽奖(可用键盘)</title><style>*{margin:0;padding:0;}.box{width: 400px;height: 300px;margin:50px auto;background: red}.title{color: #fff;font-size: 30px;font-weight:700px;padding: 50px 0;text-align: center;height:40px;}.btm{text-align: center;padding:20px 0;}.btm a{display: inline-block;width: 120px;height:60px;line-height: 60px;background: #FEF097;margin:0 10px;text-decoration: none;}</style><script>var data=["Iphone","Ipad","笔记本","相机","谢谢参与","充值卡","购物券"],timer=null,//定时器flag=0;//阻止多次回车window.onload=function(){var play=document.getElementById("play"),stop=document.getElementById("stop");// 开始抽奖play.onclick=playFun;stop.onclick=stopFun;// 键盘事件document.onkeyup=function(event){event = event || window.event;// 回车键的code值:13if(event.keyCode==13){if(flag==0){playFun();flag=1; }else{stopFun();flag=0; } }}function playFun(){var title=document.getElementById("title");var play=document.getElementById("play");clearInterval(timer);timer=setInterval(function(){var random=Math.floor(Math.random()*data.length);title.innerHTML=data[random];},60);play.style.background="#999";}function stopFun(){clearInterval(timer);var play=document.getElementById("play");play.style.background="#FEF097";}}</script></head><body><div class="box"><div class="title" id="title">淘家趣抽奖</div><div class="btm"><a href="javascript:;" id="play">开始</a><a href="javascript:;" id="stop">停止</a></div></div></body></html>
注意点:
1.随机数,取数组的其中一个;取0-n之间:Math.random()*(n+1)
2.定时器,开始抽奖时要停止前面的一次抽奖,不然会定时器重叠
3.按键操作,要判断是抽奖进行中,还是未开始,所有设置了变量 flag 
想要学习更多关于javascript抽奖功能,请参考此专题:javascript实现抽奖功能
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。