做了一個抽獎的小東西,開始和停止的按鈕是button標籤的。當我用滑鼠按下開始,輸入完人數之後,按回車暫停是可以的,但再按一次回車會開始後瞬間停止,而不是我再按一次回車才結束,如果不用button標籤的話是可以的,又或者是我先點擊了一下頁面再按回車也不瞬間停止,想知道為什麼?
代碼:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>抽奖</title>
<style type="text/css">
*{
margin:0 0;
padding:0;
font-family: "微软雅黑";
}
h1{margin-top:20px;text-align: center;}
#content{
margin: 0 auto;
text-align: center;
}
#show{
margin: 10px auto;
padding: 20px;
text-align: center;
font-size: 300px;
}
.btn{
margin-top: 10px;
}
.btn li{
display: inline-block;
width:220px;
}
.btn button{
border: 2px outset #fff;
background: #000;
letter-spacing: 2px;
padding: 5px 8px;
color: #FFF;
font-size: 18px;
font-weight: bold;
border-radius:5px;
outline:none;
cursor: pointer;
width: 150px;
text-align: center;
}
#footer{
margin-top: 65px;
}
</style>
<script type="text/javascript">
var timer=null;
var num=0;
var flag=0;
window.onload=function(){
start=document.getElementById("start");
stop=document.getElementById("stop");
showNum=document.getElementById("show");
start.onclick = playFun;
stop.onclick = stopFun;
document.onkeyup=function(event){
var event = event || window.event;
if(event.keyCode==13){
if(!flag){
playFun();
}
else {
stopFun();
console.log(flag);
}
}
}
}
function playFun (){
if(!num){
num = window.prompt("参加这次抽奖的人数:");
if(!num){
playFun();
}
}
clearInterval(timer);
timer = setInterval(function(){
var random = Math.floor(Math.random()*num+1);
showNum.innerHTML=random;
},50);
showNum.style.background = '#FFF';
showNum.style.color = '#000';
flag=1;
}
function stopFun (){
clearInterval(timer);
showNum.style.background = '#000';
showNum.style.color = '#FFF';
flag=0;
}
</script>
</head>
<body>
##
<h1>抽奖XD</h1>
<p id="content">
<p id="show">1</p>
<ul class="btn">
<li><button id="start">开始</button></li>
<li><button id="stop">停止</button></li>
</p>
</p>
怪我咯2017-05-18 10:56:36
原理如樓上所說,補充下答案。
function playFun (e){
e && e.target.blur()
if(!num){
num = window.prompt("参加这次抽奖的人数:");
if(!num){
playFun();
}
}
clearInterval(timer);
timer = setInterval(function(){
var random = Math.floor(Math.random()*num+1);
showNum.innerHTML=random;
},50);
showNum.style.background = '#FFF';
showNum.style.color = '#000';
flag=1;
}
function stopFun (e){
e && e.target.blur()
clearInterval(timer);
showNum.style.background = '#000';
showNum.style.color = '#FFF';
flag=0;
}