键盘事件
Posted 夏日的微笑
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了键盘事件相关的知识,希望对你有一定的参考价值。
!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD><TITLE>js 按键记录</TITLE>
<META NAME="Generator" CONTENT="EditPlus">
<META NAME="Author" CONTENT="羽殇仁">
<META NAME="Keywords" CONTENT="js 按键记录">
<META NAME="Description" CONTENT="js 按键 记录">
</HEAD>
<BODY>
<script type="text/javascript">
var keystring = "";//记录按键的字符串
function $(s){return document.getElementById(s)?document.getElementById(s):s;}
function keypress(e)
{
var currKey=0,CapsLock=0,e=e||event;
currKey=e.keyCode||e.which||e.charCode;
CapsLock=currKey>=65&&currKey<=90;
switch(currKey)
{
//屏蔽了退格、制表、回车、空格、方向键、删除键
case 8: case 9:case 13:case 32:case 37:case 38:case 39:case 40:case 46:keyName = "";break;
default:keyName = String.fromCharCode(currKey); break;
}
keystring += keyName;
}
function keydown(e)
{
var e=e||event;
var currKey=e.keyCode||e.which||e.charCode;
if((currKey>7&&currKey<14)||(currKey>31&&currKey<47))
{
switch(currKey)
{
case 8: keyName = "[退格]"; break;
case 9: keyName = "[制表]"; break;
case 13:keyName = "[回车]"; break;
case 32:keyName = "[空格]"; break;
case 33:keyName = "[PageUp]"; break;
case 34:keyName = "[PageDown]"; break;
case 35:keyName = "[End]"; break;
case 36:keyName = "[Home]"; break;
case 37:keyName = "[方向键左]"; break;
case 38:keyName = "[方向键上]"; break;
case 39:keyName = "[方向键右]"; break;
case 40:keyName = "[方向键下]"; break;
case 46:keyName = "[删除]"; break;
default:keyName = ""; break;
}
keystring += keyName;
}
$("content").innerHTML=keystring;
}
function keyup(e)
{
$("content").innerHTML=keystring;
}
document.onkeypress=keypress;
document.onkeydown =keydown;
document.onkeyup =keyup;
</script>
<input type="text" />
<input type="button" value="清空记录" onclick="$(‘content‘).innerHTML = ‘‘;keystring = ‘‘;"/>
<br/>请按下任意键查看键盘响应键值:<span id="content"></span>
</BODY>
</HTML>
代码分析:
$():根据ID获取dom
keypress(e):实现对字符码的截获,由于功能按键要用keydown获取,所以在keypress中屏蔽了这些功能按键。
keydown(e):主要是实现了对功能按键的获取。
keyup(e):展示截获的字符串。
以上是关于键盘事件的主要内容,如果未能解决你的问题,请参考以下文章