I made a small lottery thing. The start and stop buttons are button labels. When I press start with the mouse and enter the number of people, it is OK to press Enter to pause, but if I press Enter again, it will start and then stop instantly, instead of pressing Enter again to end. If the button label is not used, it will be Yes, or maybe I clicked on the page first and then pressed Enter and it didn’t stop immediately. I want to know why?
Code:
<!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>
</body>
</html>
After clicking the button once, the focus is positioned on the button. At this time, every time you press Enter, the button will be clicked twice. Changing to span will eliminate the focus problem
The principle is as mentioned above, please add the answer.
When the focus is on the button, pressing enter is equivalent to a left mouse click.
Also, the button tag is not recommended, so don’t hesitate to replace it directly