keyCode获取用户按下键盘的哪个按键
1 <!DOCTYPE HTML> 2 <html> 3 <head> 4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> 5 <title>无标题文档</title> 6 <script> 7 /* 8 onkeydown : 当键盘按键按下的时候触发 9 onkeyup : 当键盘按键抬起的时候触发10 11 event.keyCode : 数字类型 键盘按键的值 键值12 ctrlKey,shiftKey,altKey 布尔值13 当一个事件发生的时候,如果ctrl || shift || alt 是按下的状态,返回true,否则返回false14 */15 16 document.onkeydown = function(ev) {17 18 //alert(1);19 var ev = ev || event;20 //alert(ev.keyCode);21 22 }23 24 document.onclick = function(ev) {25 var ev = ev || event;26 27 alert(ev.ctrlKey);28 }29 </script>30 </head>31 32 <body>33 </body>34 </html>
键盘事件实例:
1 <!DOCTYPE HTML> 2 <html> 3 <head> 4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> 5 <title>无标题文档</title> 6 <script> 7 window.onload = function() { 8 9 var oText = document.getElementById('text1');10 var oUl = document.getElementById('ul1');11 12 oText.onkeyup = function(ev) {13 14 var ev = ev || event;15 16 //alert(this.value);17 if ( this.value != '' ) {18 19 if (ev.keyCode == 13 && ev.ctrlKey) {20 21 var oLi = document.createElement('li');22 oLi.innerHTML = this.value;23 24 if ( oUl.children[0] ) {25 oUl.insertBefore( oLi, oUl.children[0] );26 } else {27 oUl.appendChild( oLi );28 }29 30 }31 32 }33 34 }35 36 }37 </script>38 </head>39 40 <body>41 <input type="text" id="text1" />42 <ul id="ul1"></ul>43 </body>44 </html>
键盘控制div移动:
1 <!DOCTYPE HTML> 2 <html> 3 <head> 4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> 5 <title>无标题文档</title> 6 <style> 7 #div1 {width: 100px; height: 100px; background: red; position: absolute;} 8 </style> 9 <script>10 window.onload = function() {11 12 var oDiv = document.getElementById('div1');13 14 //不是所有元素都能够接收键盘事件,能够响应用户输入的元素,能够接收焦点的元素就能够接收键盘事件15 16 //onkeydown : 如果按下不抬起,那么会连续触发17 //定时器18 document.onkeydown = function(ev) {19 20 var ev = ev || event;21 22 switch(ev.keyCode) {23 case 37:24 oDiv.style.left = oDiv.offsetLeft - 10 + 'px';25 break;26 case 38:27 oDiv.style.top = oDiv.offsetTop - 10 + 'px';28 break;29 case 39:30 oDiv.style.left = oDiv.offsetLeft + 10 + 'px';31 break;32 case 40:33 oDiv.style.top = oDiv.offsetTop + 10 + 'px';34 break;35 }36 37 }38 39 }40 </script>41 </head>42 43 <body>44 <div id="div1"></div>45 </body>46 </html>
新闻热点
疑难解答