js實(shí)現(xiàn)可鍵盤控制的簡(jiǎn)單抽獎(jiǎng)程序

字號(hào):


    本文實(shí)例為大家分享了js抽獎(jiǎng)程序的編寫代碼,以及編寫注意事項(xiàng),感興趣的小伙伴們可以參考一下
    代碼:
    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <title>簡(jiǎn)單抽獎(jiǎng)(可用鍵盤)</title>
      <style>
        *{margin:0;padding:0;}
        .box{width: 400px;height: 300px;margin:50px auto;background: red}
        .title{color: #fff;font-size: 30px;font-weight:700px;padding: 50px 0;text-align: center;height:40px;}
        .btm{text-align: center;padding:20px 0;}
        .btm a{display: inline-block;width: 120px;height:60px;line-height: 60px;background: #FEF097;margin:0 10px;text-decoration: none;}
      </style>
      <script>
        var data=['Iphone','Ipad','筆記本','相機(jī)','謝謝參與','充值卡','購(gòu)物券'],
          timer=null,//定時(shí)器
          flag=0;//阻止多次回車
        window.onload=function(){
          var play=document.getElementById('play'),
            stop=document.getElementById('stop');
          // 開(kāi)始抽獎(jiǎng)
          play.onclick=playFun;
          stop.onclick=stopFun;
          // 鍵盤事件
          document.onkeyup=function(event){
            event = event || window.event;
            // 回車鍵的code值:13
            if(event.keyCode==13){
              if(flag==0){
                playFun();
                flag=1;
               }else{
                  stopFun();
                  flag=0;
               }
             }
            }
            function playFun(){
            var title=document.getElementById('title');
            var play=document.getElementById('play');
            clearInterval(timer);
            timer=setInterval(function(){
              var random=Math.floor(Math.random()*data.length);
              title.innerHTML=data[random];
            },60);
            play.style.background='#999';
          }
          function stopFun(){
            clearInterval(timer);
            var play=document.getElementById('play');
            play.style.background='#FEF097';
          }
        }
      </script>
    </head>
    <body>
      <div>
        <div id="title">淘家趣抽獎(jiǎng)</div>
        <div>
          <a href="javascript:;" id="play">開(kāi)始</a>
          <a href="javascript:;" id="stop">停止</a>
        </div>
      </div>
    </body>
    </html>
    注意點(diǎn): 
    1.隨機(jī)數(shù),取數(shù)組的其中一個(gè);取0-n之間:Math.random()*(n+1)
    2.定時(shí)器,開(kāi)始抽獎(jiǎng)時(shí)要停止前面的一次抽獎(jiǎng),不然會(huì)定時(shí)器重疊
    3.按鍵操作,要判斷是抽獎(jiǎng)進(jìn)行中,還是未開(kāi)始,所有設(shè)置了變量 flag 
    以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助