Javascript 事件对象(六)键盘事件

时间:2024-10-04 18:36:44

keyCode
获取用户按下键盘的哪个按键

 <!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>无标题文档</title>
<script>
/*
onkeydown : 当键盘按键按下的时候触发
onkeyup : 当键盘按键抬起的时候触发 event.keyCode : 数字类型 键盘按键的值 键值
ctrlKey,shiftKey,altKey 布尔值
当一个事件发生的时候,如果ctrl || shift || alt 是按下的状态,返回true,否则返回false
*/ document.onkeydown = function(ev) { //alert(1);
var ev = ev || event;
//alert(ev.keyCode); } document.onclick = function(ev) {
var ev = ev || event; alert(ev.ctrlKey);
}
</script>
</head> <body>
</body>
</html>

键盘事件实例:

 <!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>无标题文档</title>
<script>
window.onload = function() { var oText = document.getElementById('text1');
var oUl = document.getElementById('ul1'); oText.onkeyup = function(ev) { var ev = ev || event; //alert(this.value);
if ( this.value != '' ) { if (ev.keyCode == 13 && ev.ctrlKey) { var oLi = document.createElement('li');
oLi.innerHTML = this.value; if ( oUl.children[0] ) {
oUl.insertBefore( oLi, oUl.children[0] );
} else {
oUl.appendChild( oLi );
} } } } }
</script>
</head> <body>
<input type="text" id="text1" />
<ul id="ul1"></ul>
</body>
</html>

键盘控制div移动:

 <!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>无标题文档</title>
<style>
#div1 {width: 100px; height: 100px; background: red; position: absolute;}
</style>
<script>
window.onload = function() { var oDiv = document.getElementById('div1'); //不是所有元素都能够接收键盘事件,能够响应用户输入的元素,能够接收焦点的元素就能够接收键盘事件 //onkeydown : 如果按下不抬起,那么会连续触发
//定时器
document.onkeydown = function(ev) { var ev = ev || event; switch(ev.keyCode) {
case 37:
oDiv.style.left = oDiv.offsetLeft - 10 + 'px';
break;
case 38:
oDiv.style.top = oDiv.offsetTop - 10 + 'px';
break;
case 39:
oDiv.style.left = oDiv.offsetLeft + 10 + 'px';
break;
case 40:
oDiv.style.top = oDiv.offsetTop + 10 + 'px';
break;
} } }
</script>
</head> <body>
<div id="div1"></div>
</body>
</html>