js實現可鍵盤控制的簡單抽獎程式_javascript技巧

來源:互聯網
上載者:User

本文執行個體為大家分享了js抽獎程式的編寫代碼,以及編寫注意事項,感興趣的小夥伴們可以參考一下

 

代碼:

<!DOCTYPE html><html lang="en"><head>  <meta charset="UTF-8">  <title>簡單抽獎(可用鍵盤)</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','筆記本','相機','謝謝參與','儲值卡','購物券'],      timer=null,//定時器      flag=0;//阻止多次斷行符號    window.onload=function(){      var play=document.getElementById('play'),        stop=document.getElementById('stop');      // 開始抽獎      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 class="box">    <div class="title" id="title">淘家趣抽獎</div>    <div class="btm">      <a href="javascript:;" id="play">開始</a>      <a href="javascript:;" id="stop">停止</a>    </div>  </div></body></html>

注意點:
1.隨機數,取數組的其中一個;取0-n之間:Math.random()*(n+1)
2.定時器,開始抽獎時要停止前面的一次抽獎,不然會定時器重疊
3.按鍵動作,要判斷是抽獎進行中,還是未開始,所有設定了變數 flag 

想要學習更多關於javascript抽獎功能,請參考此專題:javascript實現抽獎功能

以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支援雲棲社區。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.