Blogger Information
Blog 250
fans 3
comment 0
visits 321720
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
JS--键盘事件
梁凯达的博客
Original
993 people have browsed it

 

实例

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
</head>
<body>
	
</body>
<script>

document.onkeydown = function(e){
	var e =  e || event;
	//alert(e.keyCode);
	//alert(e.shiftKey);
	if(e.shiftKey){
		if (e.keyCode == 65) {
			alert('我按了一下A键')
		}
	}
	console.log('我按下了键盘')
}
document.onkeyup = function(){
	console.log('我松开了键盘')
}
document.onkeypress = function(){
	console.log('按了一次键盘')
}
</script>
</html>

实例

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
	<style>
		*{margin:0px;padding:0px;}
		#box{width:100px;height:100px;position:absolute;/*background:pink;*/}
		#parent{width:400px;height:400px;border:1px solid red;background-image:url(./bg.jpg);}
	</style>
</head>
<body>
<div id="parent">
	<div id="box" style="left:0px;top:0px;">
		<img src="./me.png" alt="">
	</div>
</div>
	
</body>
<script>
var  box = document.getElementById('box');

//上键 38
//下键 40
//左键 37
//右键 39
document.onkeydown = function(e){
	var e  = e || event;
	//alert(e.keyCode);
	switch(e.keyCode){
		case 37:
			if((parseInt(box.style.left)-10)>0){
			//alert('按了左键')
				box.style.left = parseInt(box.style.left)-10+'px';
			}else{
				box.style.left = '0px';
			}
			break;
		case 38:
			if((parseInt(box.style.top)-10)>0){
			//alert('按了上键')
				box.style.top = parseInt(box.style.top)-10+"px";
			}else{
				box.style.top="0px";
			}
			break;
		case 39:
			//alert('按了右键')
			if(parseInt(box.style.left)< 300){
				box.style.left = parseInt(box.style.left) + 10 + 'px';
			}else{
				box.style.left= 300+'px';
			}
			break;
		case 40:
			//alert('按了下键')
			if(parseInt(box.style.top) < 300){
				box.style.top = parseInt(box.style.top) + 10 +'px';
			}else{
				box.style.top='300px';
			}
			break;
	}
}
</script>
</html>

运行实例 »

点击 "运行实例" 按钮查看在线实例

运行实例 »

点击 "运行实例" 按钮查看在线实例

 

Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post