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';
    }


其中有什么不足之处,请大家多多提出,希望能够帮助需要帮助的你!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值