JS keycode 事件响应

mac2022-06-30  215

<script language="javascript"> function keyevent(){ if(event.keyCode==13) alert("你按了回车键"); } document.onkeydown = keyevent;//注册document.onkeydown事件</script>

当用户按回车键时,就会执行keyevent()这个函数。可以做回车提交表单,或其它的事件!

keyCode是返回keydown何keyup事件发生的时候按键的代码,以及keypress 事件的Unicode字符;如果要使用组合键,则可以利用event.ctrlKey,event.shiftKey,event .altKey判断是否按下了ctrl键、shift键以及alt键.

常用keycodekeycodekeycodeleft37up38right39down40149250351a65shift16ctrl17alt18enter13

示例:

<!DOCTYPE html> <html> <head> <title>键盘事件keycode</title> </head> <body> left      up      right      down<br /> ctrl + up      ctrl + down<br /> ctrl + 1      ctrl + 2      ctrl + 3<br /> a      ctrl + a      ctrl + shift + a<br /> <script type="text/javascript"> document.onkeydown = function (event) { event = event || window.event; bCtrlKey = event.ctrlKey; bShiftKey = event.shiftKey; switch (event.keyCode) { case 37: alert("left"); break; case 38: if (bCtrlKey) { alert("ctrl+up"); break; } alert("up"); break; case 39: alert("right"); break; case 40: if (bCtrlKey) { alert("ctrl+down"); break; } alert("down"); break; case 49: bCtrlKey && (alert("ctrl+1")); break; case 50: bCtrlKey && (alert("ctrl+2")); break; case 51: bCtrlKey && (alert("ctrl+3")); break; case 65: if (bCtrlKey) { if (bShiftKey) { alert("自定义"); break; } alert("全选"); break; } alert("a"); break; case 67: bCtrlKey && (alert("复制")); break; case 86: bCtrlKey && (alert("粘贴")); break; } return false; } </script> </body> </html>

---------------------------------------------------------------------------------------------

<script language="javascript"> function keyevent(){ if(event.keyCode==13) alert("#$%#%#^^%"); } document.onkeydown = keyevent; </script> event.keyCode值为37﹐38﹐39﹐40对应按下的方向键分別是 左﹐上﹐右﹐下 "javascript:if (event.keyCode < 45 || event.keyCode > 57) event.returnValue = false;"); if(event.keycode==13)就代表按下的是回车键盘 "javascript:if (event.keyCode > 45 && event.keyCode < 57) event.returnValue = false;"); ----------------------------------------------------------------------------------------------

<参考:http://lfsp.btwlo.com/keycode.html & http://www.cnblogs.com/xingqiba/archive/2012/06/12/2546148.html & http://www.cnblogs.com/kuikui/archive/2012/02/09/2343645.html>

转载于:https://www.cnblogs.com/ChandlerVer5/p/js_keycode.html

相关资源:javascript键盘响应js

最新回复(0)