Init.Sun Chengdu.Sichuan

键盘事件

2016-12-26
Init

JS中的键盘事件,

event.keyCode:数字类型 键盘按键的值

ctrlKey,shiftKey,altKey 布尔值。当一个事件发生的时候,如果ctrl   shift   alt是按下的状态,返回true

不是所有元素都能够接收键盘事件,能够响应用户输入的元素,能够接收焦点的元素才能够接收键盘事件。

onkeydown onkeyup

当键盘按键按下的时候触发、当抬起的时候触发


<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
	<style>
		#div1{
			width: 100px;
			height: 100px;
			background: red;
			position: absolute;
		}
	</style>
</head>
<body>
	<div id="div1"></div>
</body>
<script>
	/*document.onkeyup = function(ev){
		var ev = ev|| event;
		if(ev.keyCode == 13 && ev.ctrlKey){
			alert('发送')
		}
	}*/
	var oDiv = document.getElementById('div1');
	var isLeft,isRight,isTop,isBottom;
	setInterval(function(){//使用setInterval解决停顿的问题
		if(isLeft)oDiv.style.left = oDiv.offsetLeft-10+'px';
		if(isRight)oDiv.style.left = oDiv.offsetLeft+10+'px';
		if(isTop)oDiv.style.top = oDiv.offsetTop-10+'px';
		if(isBottom)oDiv.style.top = oDiv.offsetTop+10+'px';
	},100);
	document.onkeydown = function(ev){
		var ev = ev || event;
		switch(ev.keyCode){
			case 37:
				isLeft = true;
				break;
			case 38:
				isTop = true;
				break;
			case 39:
				isRight = true;			
				break;
			case 40:
				isBottom= true;
				break;
		}
	}

	document.onkeyup = function(ev){
		var ev = ev || event;
		switch(ev.keyCode){
           case 37: isLeft = false;break;
           case 38: isTop = false;break;
           case 39: isRight = false;break;
           case 40: isBottom = false;break;
        }
	}

</script>
</html>


下一篇 2017勾坳

Comments