年末了各個公司都有抽獎活動,我也寫了一個超級簡單的代碼來實現抽獎效果,這裏沒有華麗的Css3效果,但卻有短小精悍的js代碼。核心:js的Math對象和Array對象javascript
效果圖:html
code:java
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>
demo:http://2.liteng.sinaapp.com/javascript/award.htmlgit
github:github:https://github.com/litengdesign/awardgithub