JavaScript响应键盘事件
监听键盘弹起事件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| <!DOCTYPE html> <html lang="en">
<head> <meta charset="utf-8"> <style type="text/css"> </style> <script> 监听键盘按下时间 document.onkeyup=function(){ console.log("键盘弹起"); }; </script> </head>
<body> </body>
</html>
|
打印keyCode
1 2 3 4 5 6 7
| document.onkeyup = function (event) { event = event || window.event; console.log("键盘弹起,keyCode=" + event.keyCode); };
|
使用组合键
1 2 3 4 5 6 7 8 9 10
| document.onkeyup = function (event) { event = event || window.event; if (event.keyCode === 78 && event.ctrlKey && event.altKey) { console.log('您按下了:ctrl+alt' + event.keyCode); } if ( event.altKey && event.keyCode === 78) { console.log('您按下了:alt' + event.keyCode); } };
|
响应组合键
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| <script> document.onkeyup = function (event) { if (event.altKey) { switch (event.keyCode) { case 73: input.focus(); break; case 78: niuke(); break; } } } </script>
|
JS按键和keyCode的对应关系
参考资料
https://www.bilibili.com/video/BV1cs411u7qt