1、index.html
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>简单抽奖系统-使用键盘事件</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
<script type="text/javascript" src="js/script.js"></script>
</head>
<body>
<div id="title" class="title">开始抽奖了!</div>
<div class="btns">
<span id="play">开 始</span>
<span id="stop">停 止</span>
</div>
</body>
</html>
2、css/style.css
*{
margin:0;
padding: 0;
}
.title{
width:400px;
height:70px;
margin: 0 auto;
text-align: center;
padding-top: 30px;
font-size: 24px;
font-weight: bold;
color: red;
}
.btns{
width: 190px;
height: 30px;
margin: 0 auto;
}
.btns span{
display: block;
float:left;
width:80px;
height:27px;
line-height: 27px;
margin-right: 10px;
text-align: center;
background-color: blue;
color: #fff;
border: 1px solid red;
border-radius: 7px;
font-size:14px;
font-family:"微软雅黑";
cursor:pointer;
}
3、js/script.js
var data=['Phone5','Ipad','三星笔记本','佳能相机','惠普打印机','谢谢参与','50元充值卡','1000元超市购物券'],
timer=null,//全局变量计时器
flag=0;//全局变量Boolean值,用来判断回车键执行的逻辑,保证前后两次互斥
window.onload = function(){
var oTitle = document.getElementById('title'),//中奖文本区域
play = document.getElementById('play'),//开始按钮
stop = document.getElementById('stop');//停止按钮
play.onclick = playFun;
stop.onclick = stopFun;
document.onkeyup = function(event){
event = event?event:window.event;
if(event.keyCode==13){//回车键松开事件
if(flag==0){
playFun();
}else{
stopFun();
}
}
}
function playFun(){
clearInterval(timer);//先清计时器,存在多次点击开始按钮,每点击一次生成一个新的计时器的情况,所以先清
timer = setInterval(function(){
var random = Math.floor(Math.random()*data.length);
oTitle.innerHTML = data[random];
},50);
play.style.background = '#999';
flag = 1;
}
function stopFun(){
clearInterval(timer);
play.style.background = 'blue';
flag = 0;
}
}
热门评论
这个代码有bug,在浏览器多试试就知道。我弄很久bug都弄吧了