1 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> 2 <HTML> 3 <HEAD> 4 <TITLE>js 按键记录</TITLE> 5 </HEAD> 6 <BODY> 7 <script type="text/javascript"> 8 var keystring = "";//记录按键的字符串 9 function $(s) { return document.getElementById(s) ? document.getElementById(s) : s; } 10 function keypress(e) { 11 var currKey = 0, CapsLock = 0, e = e || event; 12 currKey = e.keyCode || e.which || e.charCode; 13 CapsLock = currKey >= 65 && currKey <= 90; 14 switch (currKey) { 15 //屏蔽了退格、制表、回车、空格、方向键、删除键 16 case 8: case 9: case 13: case 32: case 37: case 38: case 39: case 40: case 46: keyName = ""; break; 17 default: keyName = String.fromCharCode(currKey); break; 18 } 19 keystring += keyName; 20 } 21 function keydown(e) { 22 var e = e || event; 23 var currKey = e.keyCode || e.which || e.charCode; 24 if ((currKey > 7 && currKey < 14) || (currKey > 31 && currKey < 47)) { 25 switch (currKey) { 26 case 8: keyName = "[退格]"; break; 27 case 9: keyName = "[制表]"; break; 28 case 13: keyName = "[回车]"; break; 29 case 32: keyName = "[空格]"; break; 30 case 33: keyName = "[PageUp]"; break; 31 case 34: keyName = "[PageDown]"; break; 32 case 35: keyName = "[End]"; break; 33 case 36: keyName = "[Home]"; break; 34 case 37: keyName = "[方向键左]"; break; 35 case 38: keyName = "[方向键上]"; break; 36 case 39: keyName = "[方向键右]"; break; 37 case 40: keyName = "[方向键下]"; break; 38 case 46: keyName = "[删除]"; break; 39 default: keyName = ""; break; 40 } 41 keystring += keyName; 42 } 43 $("content").innerHTML = keystring; 44 } 45 function keyup(e) { 46 $("content").innerHTML = keystring; 47 } 48 document.onkeypress = keypress; 49 document.onkeydown = keydown; 50 document.onkeyup = keyup; 51 </script> 52 <input type="text" /> 53 <input type="button" value="清空记录" onclick="$('content').innerHTML = '';keystring = '';" /> 54 <br />请按下任意键查看键盘响应键值:<span id="content"></span> 55 </BODY> 56 </HTML>