做web开发的时候,有时候需要根据键盘进行一些操作,例如按下Enter的时候提交表单,禁止用户输入某些特殊字符,设置快捷键等等。这时候需要找出用户按下的是那些按键,每次都找对照表太麻烦了.so..写了这么个小程序来测试按键。^_^
其中的charCode是根据ascii表转换的,不一定准确。
| keyCode : | |
| charCode : | |
| shift-key : | |
| ctrl-key : | |
| alt-key : |
下面是ascii编码表:

源代码:
<script type=”text/javascript”>
function showKey(e){
e
= e || window.event;document.getElementById(
“keyCode“).value = e.keyCode;document.getElementById(
“charCode“).value = String.fromCharCode(e.keyCode);document.getElementById(
“shiftKey“).value = e.shiftKey;document.getElementById(
“ctrlKey“).value = e.ctrlKey;document.getElementById(
“altKey“).value = e.altKey;}
$(document).ready(
function(){document.onkeydown
= showKey;});
</script> <br /> <table> <tbody> <tr> <td>keyCode : </td> <td><input id=”keyCode” type=”text” /> </td> </tr> <tr> <td>charCode : </td> <td><input id=”charCode” type=”text” /> </td> </tr> <tr> <td>shift-key : </td> <td><input id=”shiftKey” type=”text” /> </td> </tr> <tr> <td>ctrl-key : </td> <td><input id=”ctrlKey” type=”text” /> </td> </tr> <tr> <td>alt-key : </td> <td><input id=”altKey” type=”text” /> </td> </tr> </tbody> </table>其中我使用了jquery来初始化document的onkeydown事件。如果你不使用jquery可以用下面这段代码
window.onload = function(){
document.onkeydown
= showKey;};
代替
$(document).ready(function(){
document.onkeydown
= showKey;});
0 Responses to “测试你按下的是那个键”
Leave a Reply