製作一個簡易的抽獎系統!歡迎大家學習!
JS原理:建立一個數組用來儲存抽獎內容,例如 iphone6 等,當點擊開始的時候,開啟定時器,產生一個隨機數,把對應文本的innerHTML改成數組所對應的內容。
如果想讓某個抽獎幾率變高,可以讓數組中某個值重複次數多點。接下來看代碼。、
JavaScript代碼
window.onload = function(){ var data = [ "iphone 6s plus", "蘋果Mac 筆記本", "美的洗衣機", "淩美鋼筆", "謝謝參與", "索尼入耳式耳機", "雷柏機械鍵盤", "《javaScript進階程式設計》", "精美保溫杯", "維尼小熊一隻", "500元中國石化加油卡", "愛奇藝年費會員", "iPad mini", "32G 隨身碟", ]; var bStop = true; var timer = null; var btns = document.getElementById('btns').getElementsByTagName('span'); var text = document.getElementById('text'); btns[0].onclick = start; btns[1].onclick = stop; document.onkeyup = function(event){ event = event||window.event; if(event.keyCode==13){ if(bStop){ start(); }else { stop(); } } } function start(){ clearInterval(timer); timer = setInterval(function(){ var r = Math.floor(Math.random()*data.length); text.innerHTML = data[r]; },20); btns[0].style.background = '#666'; bStop = false; } function stop(){ clearInterval(timer); btns[0].style.background = 'blue'; bStop = true; }}
html css 代碼:
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>抽獎啦</title> <style> * { margin: 0; padding:0; } #container { width: 500px; height: 200px; margin: 100px auto; background: red; position: relative; padding-top: 20px; } #container p { position: absolute; bottom: 4px; left: 30px; } #btns { position: absolute; left: 118px; bottom: 30px; } #container h1 { color: #fff; text-align: center; } #btn-start,#btn-stop { width: 100px; height: 60px; background: blue; text-align: center; line-height: 60px; font-size: 20px; display: inline-block; color: #fff; margin-right: 60px; border-radius: 10px; cursor: pointer; } </style> <script src="index.js"></script></head><body> <div id="container"> <h1 id="text">iphone 6s plus</h1> <p>小提示:您可以按下Enter鍵來控制開始暫停,祝您中大獎喲</p> <div id="btns"> <span id="btn-start">開始</span> <span id="btn-stop">停止</span> </div> </div></body></html>
希望本文所述對大家的學習有所協助,輕鬆實現抽獎系統。