javascript - 在利用button标签时,鼠标事件和键盘事件切换会出错?
本文介绍了javascript - 在利用button标签时,鼠标事件和键盘事件切换会出错?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
做了一个抽奖的小东西,开始和停止的按钮是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>
<div id="content">
<div id="show">1</div>
<ul class="btn">
<li><button id="start">开始</button></li>
<li><button id="stop">停止</button></li>
</div>
</div>
</body>
</html>
解决方案
原理如楼上所说,补充下答案。
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;
}
这篇关于javascript - 在利用button标签时,鼠标事件和键盘事件切换会出错?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文