做web開發的時候,有時候需要根據鍵盤進行一些操作,例如按下Enter的時候提交表單,禁止用戶輸入某些特殊字符,設置快捷鍵等等。這時候需要找出用戶按下的是那些按鍵,每次都找對照表太麻煩了.so..寫了這么個小程序來測試按鍵。^_^
其中的charCode是根據ascii表轉換的,不一定準確。
下面是ascii編碼表:

源代碼:
代替
其中的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可以用下面這段代碼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>
window.onload = function(){
document.onkeydown = showKey;
};
document.onkeydown = showKey;
};
代替
$(document).ready(function(){
document.onkeydown = showKey;
});
document.onkeydown = showKey;
});