js簡單抽獎代碼,js抽獎
核心:js的Math對象和Array對象
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>random</title> <style> #awardListDom{width: 100%;} </style></head><body> <label for="awardListDom">獎項列表</label><br> <input type="text" value="" id="awardListDom"> <br> <label for="num">抽到的獎</label><br> <input type="text" value="" id="num"> <br> <button id="submit">開始抽獎</button> <script> /* * 思路:隨機抽獎,抽一個獎項便減少一個 * Math 對象方法:http://www.w3school.com.cn/jsref/jsref_obj_math.asp * -random():返回 0 ~ 1 之間的隨機數。 * -floor():擷取整數 * 數組操作: * - splice(x,y); x:起始位置, y:擷取並刪除個數 */ function random(min,max){ return Math.floor(min+Math.random()*(max-min)); } var awardListDom=document.getElementById("awardListDom"), num=document.getElementById("num"), submit=document.getElementById("submit"); var awardList=["一等獎","二等獎","二等獎","三等獎","三等獎","三等獎","鼓勵獎","鼓勵獎","鼓勵獎","鼓勵獎","謝謝參與","謝謝參與","謝謝參與","謝謝參與","謝謝參與","謝謝參與"]; awardListDom.value=awardList; submit.onclick=function(){ //引用數組 var oldArray=awardList; var rNum=random(0,oldArray.length); if(oldArray.length<1){ awardListDom.value="活動結束"; num.value="活動結束"; } else{ num.value=oldArray[rNum]; oldArray.splice(rNum,1); awardListDom.value=oldArray; } } </script></body></html>
demo:http://demo.jb51.net/js/2015/choujiang/
github:https://github.com/litengdesign/award