1. 程式人生 > 其它 >js鍵盤事件

js鍵盤事件

onkeydown:當鍵盤按鍵按下的時候觸發

onkeyup:當鍵盤按鍵抬起的時候觸發

event.keyCode:數字型別 鍵盤按鍵的值 鍵值

不是所有元素都能夠接收鍵盤事件,能夠響應使用者輸入的元素,能夠接收焦點的元素就能接收鍵盤事件
onkeydown:如果按下不抬起,那麼會連續觸發

數字鍵盤上的鍵的鍵碼值(keyCode)功能鍵鍵碼值(keyCode)
按鍵鍵碼按鍵鍵碼按鍵鍵碼按鍵鍵碼
0 96 8 104 F1 112 F7 118
1 97 9 105 F2 113 F8 119
2 98 * 106 F3 114 F9 120
3 99 + 107 F4 115 F10 121
4 100 Enter 108 F5 116 F11 122
5 101 - 109 F6 117 F12 123
6 102 . 110
7 103 / 111

字母和數字鍵的鍵碼值(keyCode)

按鍵鍵碼

A65J74S83149B66K75T84250C67L76U85351D68M77V86452E69N78W87553F70O79X88654G71P80Y89755H72Q81Z90856I73R82048957

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="
UTF-8"> 5 <title>Title</title> 6 <style> 7 #box { 8 width: 400px; 9 height: 600px; 10 border: 1px solid; 11 margin: 50px auto 0; 12 position: relative 13 } 14 15 #tank { 16 width: 50px;
17 height: 50px; 18 position: absolute; 19 left: 175px; 20 bottom: 0; 21 background: darkgreen 22 } 23 </style> 24 </head> 25 <body> 26 <div id="box"> 27 <div id="tank"></div> 28 </div> 29 </body> 30 </html> 31 <script> 32 var box=document.getElementById('box') 33 var tank=document.getElementById('tank') 34 document.onkeydown=function(event) 35 //回車鍵 鍵值為13 36 { 37 if(event.keyCode==37) { 38 39 /*if(tank.offsetLeft<=0){ 40 tank.style.left=0*/ 41 42 // 三目運算子 43 tank.style.left = tank.offsetLeft > 0 ? tank.offsetLeft - 3 + 'px' : 0 44 45 } 46 /* else { 47 tank.style.left=tank.offsetLeft - 3 + 'px' 48 }*/ 49 50 if(event.keyCode==39){ 51 52 /* if(tank.offsetLeft>=box.offsetWidth-tank.offsetWidth){ 53 tank.style.left= box.offsetWidth-tank.offsetWidth+'px' 54 }else {*/ 55 // 三目運算子 56 tank.style.left=tank.offsetLeft <box.offsetWidth-tank.offsetWidth?tank.offsetLeft+ 3 + 'px':box.offsetWidth-tank.offsetWidth 57 } 58 } 59 /* document.onkeydown=function (event) { 60 console.log(event.keyCode) 61 }*/ 62 // up dowm press(視窗沒有事件) 63 </script>