JS keyboard key event, continue operation after releasing

Brief introduction of the code to press until it is released before proceeding

Function introduction:

Enter the method, press the space, and output the record. If it is not released within 5s, a prompt will pop up. If it is released, the keyboard release event will be cleared, the timer will be cleared, and the number of records will be entered into the next cycle. Conditions can be added to the bouncing method to determine when to end the loop.

<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
<title></title> 
 <script type="text/javascript" src="js/jquery-1.11.0.min.js"></script>

 </head>
 
 <body>
  
 	<script type="text/javascript">
			 var startTime;//开始时间点
			 var endTime//结束时间点
			 var count=0;//循环次数			  
			 var countTimeOut;//定时器
			 
			//开始	
		$(function(){
			begin();
			
			})	
			
		function begin(){		
		//键盘按下事件
				$(document).keydown(function(){
 						if(event.keyCode == 32){
						countTimeOut=setTimeout(function(){
							 alert("按这么长时间,累了吧,松开吧!")
						},5000)
						console.log("按了")
						startDate=(new Date()).getTime();
					 	$(document).unbind("keydown"); //清除键盘事件					
					}
 				
				});				
			//键盘弹起事件
				$(document).keyup(function(){
 						if(event.keyCode == 32){
 							console.log("============"
							+"弹起来了")
							clearTimeout(countTimeOut);//清除定时器
						$(document).unbind("keyup"); 	//清除键盘事件
						count++	
						console.log("count=="+count)
						begin();//重新开始							 
 						}
 					});			
		}					   		   
		</script>
 
 </body> 
 
 
 
 </html>
Published 4 original articles · received 1 · views 487

Guess you like

Origin blog.csdn.net/weixin_44760375/article/details/102835263