floor random 隨機抽獎

今天我在學習javascript的random 和 floor的時候想起用這個兩個來寫一個簡單的隨機抽獎頁面。

寫出的效果如下所示:


點擊開始抽獎的時候上面紅色部分的獎品會隨機變化,點擊停止的時候就顯示你抽中的獎品是什麼,做個其實很簡單的,但是首先還是要把思路理清楚,那樣寫起來就不覺得那麼難。

1、首先要定義一個數組,裏面放置獎品清單,

2、在兩個按鈕上設置點擊事件(點擊過後注意按鈕的顏色背景變化),

3、設置定時器,然後在裏面設置事件變化代碼,這樣裏面的獎品纔會不斷的滾動,這裏就是需要用的random  和 floor

4、停止的時候清楚定期器,

完整的代碼如下所示:

html代碼:

<div class="box">  
    <div class="drag" id="drag">按下可以拖動</div>
    <div id="title" class="title">開始抽獎啦!</div>
    <div class="btns">
       <span id="play">開 始</span>
       <span id="stop">停 止</span>
    </div> 
</div>


css代碼:

body{ font-family: 'Microsoft Yahei';}
    div{margin:0; padding:0;}
    .box{ width: 500px;height: 300px; border:1px solid red; margin:50px auto;}
    .drag{ height: 50px; line-height: 50px; background:#f4bcbc; text-align: center; width: 200px; margin:0 auto; cursor:move; }

    .title{ height: 60px;line-height: 60px; font-size: 16px; color: #ff0000; text-align: center; background: pink;}
    .btns{ text-align: center;}
    .btns span{ display: block; width: 60px; height: 35px; line-height: 35px; border-radius: 5px; 
        background:#0e6ef0; margin-left: 10px; float: left; text-align: center; color: #fff; margin-top: 10px; cursor: pointer;}
    .btns span:first-child{ margin-left: 180px;}


javascript代碼:

//定義一個數組 ,裏面放置獎品內容
    var prize=['Iphone6 plus','康佳電視','小米手環','跑步機','冰箱','洗衣機','三星筆記本','100元購物卡'];
        timer=null,flag=0;
    var play=document.getElementById('play'),
        stop=document.getElementById('stop'),
        title=document.getElementById("title");
    window.οnlοad=function(){
        //開始抽獎啦!
        play.οnclick=playFun;
        stop.οnclick=stopFun;
        // 鍵盤事件
        document.οnkeyup=function(event){
            event = event || window.event;
            if(event.keyCode==13){
                if(flag==0){
                    playFun();
                     flag=1;
            }else{
                stopFun();
                flag=0;
             }
          }
        }
    }
    //開始抽獎方法
    function playFun(){
        clearInterval(timer);
        timer=setInterval(function(){
            //由於random取到的是屬於0到1之間的小數,然後在用floor向下取整
            var random=Math.floor(Math.random()*prize.length);

            title.innerHTML=prize[random];
        }, 10);
        play.style.background='#5195f1';
    }
    //停止抽獎方法
    function stopFun(){
         play=document.getElementById("play");
        clearInterval(timer);
        play.style.background='#0e6ef0';
    }


其中有什麼不足之處,請大家多多提出,希望能夠幫助需要幫助的你!

發佈了20 篇原創文章 · 獲贊 25 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章