For non-printable keys such as arrow keys and shortcut keys such as Ctrl-z, Ctrl-x, Ctrl-c that may trigger some action in the browser (for instance, inside editable documents or elements), you may not get a keypress event in all browsers. For this reason you have to use keydown
instead, if you're interested in suppressing the browser's default action. If not, keyup
will do just as well.
Attaching a keydown
event to document
works in all the major browsers:
document.onkeydown = function(evt) {
evt = evt || window.event;
if (evt.ctrlKey && evt.keyCode == 90) {
alert("Ctrl-Z");
}
};
For a complete reference, I strongly recommend Jan Wolter's article on JavaScript key handling.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…