js简单抽奖代码
年底了各个公司都有抽奖活动,我也写了一个超级简单的代码来实现抽奖效果,这里没有华丽的Css3效果,但却有短小精悍的js代码。核心:js的Math对象和Array对象
效果图:
code:
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>random</title> 6 <style> 7 #awardListDom{width: 100%;} 8 </style> 9 </head> 10 <body> 11 <label for="awardListDom">奖项列表</label><br> 12 <input type="text" value="" id="awardListDom"> <br> 13 <label for="num">抽到的奖</label><br> 14 <input type="text" value="" id="num"> <br> 15 <button id="submit">开始抽奖</button> 16 <script> 17 /* 18 * 思路:随机抽奖,抽一个奖项便减少一个 19 * Math 对象方法:http://www.w3school.com.cn/jsref/jsref_obj_math.asp 20 * -random():返回 0 ~ 1 之间的随机数。 21 * -floor():获取整数 22 * 数组操作: 23 * - splice(x,y); x:起始位置, y:获取并删除个数 24 */ 25 26 function random(min,max){ 27 return Math.floor(min+Math.random()*(max-min)); 28 } 29 var awardListDom=document.getElementById("awardListDom"), 30 num=document.getElementById("num"), 31 submit=document.getElementById("submit"); 32 var awardList=["一等奖","二等奖","二等奖","三等奖","三等奖","三等奖","鼓励奖","鼓励奖","鼓励奖","鼓励奖","谢谢参与","谢谢参与","谢谢参与","谢谢参与","谢谢参与","谢谢参与"]; 33 34 awardListDom.value=awardList; 35 submit.onclick=function(){ 36 //引用数组 37 var oldArray=awardList; 38 var rNum=random(0,oldArray.length); 39 40 if(oldArray.length<1){ 41 awardListDom.value="活动结束"; 42 num.value="活动结束"; 43 } 44 else{ 45 num.value=oldArray[rNum]; 46 oldArray.splice(rNum,1); 47 awardListDom.value=oldArray; 48 } 49 } 50 </script> 51 </body> 52 </html>
if you don't try,you will never know!