键盘事件和一个抽奖的小例子
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>choujiang</title>
<style type='text/css'>
#title{
width: 500px;
text-align: center;
font-size: 24px;
font-weight: bold;
margin: 20px auto;
}
.btns{
width: 290px;
margin: 20px auto;
}
.btns button{
font-weight: bold;
display: inline-block;
margin-left: 50px;
font-size: 15px;
text-align: center;
width: 80px;
height: 30px;
border: 1px solid ;
border-radius: 5px;
line-height: 25px;
color: #fff;
background-color: red;
}
</style>
<script type="text/javascript">
var content = ["xiong","ying","cai","chen","yang","xin","yun","xiao","gou","liang","hui","zhou"];
var length = content.length;
var timer;
var flag = 'true';//这里会设置一个变量,用来判断当前按下的enter键是奇数次还是偶数次,因为奇数次执行开始抽奖
window.onload = function(){
var play = document.getElementById("btn1");
var stop = document.getElementById("btn2");
var title = document.getElementById("title");
play.onclick = sClick;
stop.onClick = pClick;
}
document.onkeyup = function(event){
event = event || window.event;
if(event.keyCode == 13){//keyCode == 13代表的就是enter键,事件对象中可以使用console.log(event.keyCode)来查看我们按下键的keyCode
if(flag == 'true' ){
sClick();
flag = 'false';
}else {
pClick();
flag = 'true';
}
}
}
function sClick(){
var play = document.getElementById("btn1");
clearInterval(timer);//这里一定要记得在添加一个定时器之前要先把之前的的定时器给删掉,不然会不断的添加定时器,从而使速度越来越快
timer = setInterval(function(){
var t = Math.floor(Math.random()*length);
title.innerHTML = content[t];
},50)
play.style.background = 'rgba(255,0,0,0.3)';
}
function pClick(){
var play = document.getElementById("btn1");
clearInterval(timer);
play.style.background = 'rgba(255,0,0,1)';
}
</script>
</head>
<body>
<div class="title" id="title">we will start</div>
<div class="btns">
<button id="btn1" onclick="sClick()">start</button>
<button id="btn2" onclick="pClick()">stop</button>
</div>
</body>
</html>