今天我在学习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>
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;}
//定义一个数组 ,里面放置奖品内容
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';
}
其中有什么不足之处,请大家多多提出,希望能够帮助需要帮助的你!