制作一個簡易的抽獎系統(tǒng)!歡迎大家學(xué)習(xí)!

JS原理:建立一個數(shù)組用來存儲抽獎內(nèi)容,例如 iphone6 等,當(dāng)點擊開始的時候,開啟定時器,產(chǎn)生一個隨機數(shù),把對應(yīng)文本的innerHTML改成數(shù)組所對應(yīng)的內(nèi)容。
如果想讓某個抽獎幾率變高,可以讓數(shù)組中某個值重復(fù)次數(shù)多點。接下來看代碼。、
JavaScript代碼
window.onload = function(){  var data = [    "iphone 6s plus",    "蘋果Mac 筆記本",    "美的洗衣機",    "凌美鋼筆",    "謝謝參與",    "索尼入耳式耳機",    "雷柏機械鍵盤",    "《javaScript高級程序設(shè)計》",    "精美保溫杯",    "維尼小熊一只",    "500元中國石化加油卡",    "愛奇藝年費會員",    "iPad mini",    "32G U盤",  ];  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>希望本文所述對大家的學(xué)習(xí)有所幫助,輕松實現(xiàn)抽獎系統(tǒng)。
新聞熱點
疑難解答