本文涉及語法:
onkeydown //當鍵盤按下 onkeyup //當鍵盤被松開 onkeypress //按鍵被按下並釋放一個鍵時 even.keyCode //獲取鍵盤碼 String.fromCharCode() //可接受一個可指定的unicode值,返回一個字符串
代碼如下:
<!doctype html> <html lang="zh-en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>原生JavaScript鍵盤事件</title> <link rel="icon" href="http://tools.renpengpeng.com/favicon.ico" /> <style> *{ padding:0; padding-top:10px; margin:0; text-align:center; } #jp,#jptxt { margin-top:30px; width:500px; heihgt:300px; margin:0 auto; } </style> </head> <body> <div id="jp">請按下鍵盤</div> <div id="jptxt"></div> <script> //獲取鍵盤按下並激活函數 document.onkeydown = function(even){ //獲取鍵盤碼 var jpCode = even.keyCode; //獲取鍵盤上的字母鍵盤的字母 var keychar=String.fromCharCode(jpCode); alert(keychar); //把頁面上的id聲明到變量中 var jpCodeTxt = document.getElementById('jptxt') //打印鍵盤碼到頁面上 document.getElementById('jp').innerHTML = jpCode; //開始switch循環 ** 用於中文提示 switch(jpCode){ case 8: jpCodeTxt.innerHTML = "你按了刪除鍵(Backspace)"; break; case 13: jpCodeTxt.innerHTML = "你按了確定鍵(Enter)"; break; case 18: jpCodeTxt.innerHTML = "你按了ALT"; break; default: jpCodeTxt.innerHTML = "鬼知道你按了什么"; break; } } </script> </body> </html>

轉自:https://blog.csdn.net/u012038147/article/details/78120922?locationNum=8&fps=1
