Home > Article > Web Front-end > Example code for monitoring keyboard events using js and jquery_javascript skills
The project needs to monitor the keyboard key combination CTRL C in order to respond accordingly. I checked some methods, but their compatibility and stability are not very high. Finally, I got the following method, which has been tested and can be used in Firfox, Chrome, and IE.
1. Use javascript to implement
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> <script> function keyListener(event){ if (event.ctrlKey && event.keyCode === 86){ alert('你按下了CTRL+V'); } } </script> </head> <body> Ctrl+V:<textarea onkeydown="keyListener(event);">粘贴粘贴</textarea> </body> </html>
2. Use jquery to implement
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> <script src="http://tztest4.ptmind.cn/js/jquery-1.8.0.min.js?v=3/11"></script> <script> $(function(){ $("#aaa").keyup(function(event){ if (event.ctrlKey && event.keyCode === 67){ alert('你按下了CTRL+C'); } }); }); /* * $('input').keyup(function(){...}); * $('input').bind('keyup', function(){...}); * $('input').live('keyup', function(){...}); */ </script> </head> <body> Ctrl+C:<textarea id="aaa">复制复制</textarea> <br /> </body> </html>
3. Instructions
event.ctrlKey
Function: Detect whether the Ctrl key is pressed when the event occurs.
Syntax: event.ctrlKey
Value: true | false 1|0
Instructions:
If the ctrlKey attribute is true, it means that the Ctrl key was pressed and held when the event occurred. If it is false, the Ctrl key was not pressed.
The ctrlKey attribute can be used in combination with the mouse or keyboard, and is mostly used to create some shortcut operations.
4. Detailed keyCode value list
The above is the sample code for monitoring keyboard events with js and jquery. I hope it will be helpful to everyone's learning.