This article shares the code and precautions for writing js lottery programs. Interested friends can refer to it.
Code:
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Simple lottery (keyboard available)</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','lapbook','camera','thanks for participation','recharge card','s shopping voucher'], timer=null,//timer flag=0;//prevent multiple carriage return window.onload=function(){ var play=document.getElementById('play'), stop=document.getElementById('stop'); // start the draw play.onclick=playFun; stop.onclick=stopFun; // keyboard event document.onkeyup=function(event){ event = event || window.event; // code value of the Enter key: 13 if(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> <div id="title">Taojia Fun Lottery</div> <div> <a href="javascript:;" id="play">Start</a> <a href="javascript:;" id="stop">Stop</a> </div> </div></body></html>Note:
1. Random number, take one of the array; take between 0-n: Math.random()*(n+1)
2. Timer. When starting the lottery, stop the previous lottery, otherwise the timers will overlap.
3. Press the key operation, to determine whether the lottery is in progress or not, all variable flags are set
If you want to learn more about the JavaScript lottery function, please refer to this topic: JavaScript implements the lottery function
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.