问题
Is there any way to prevent a key like F1 from being pressed?
After a short search, I found this website:
http://www.cambiaresearch.com/c4/789d4357-60e9-4dbd-8e8c-affb2ebd6960/How-Do-I-Suppress-a-Keystroke-in-a-Browser-Input-Box-Using-Javascript.aspx
This way one can suppress keys like 'a' being pressed (it does not get put in the textbox), but keys like 'tab', 'F1' etc. are still working, i.e. the focus does change and, as I'm using Google Chrome, the Chrome help website does pop up.
I'm specifically talking about Google Chrome; the solution does not have to work in other browsers too.
Is this possible at all, and if so, how?
Thanks.
回答1:
keypress
is not necessarily triggered when the keypress is not a character. So the browser may not trigger an event on backspace, F1, the down key, etc.
Try cancelling events on keydown
instead:
element.addEventListener('keydown', function(e) {
if (e.which === 112) { // F1 pressed
e.preventDefault(); // cancel the event
}
}
Note that this will work in Chrome and other standards-compliant browsers, but not in Internet Explorer <9.
回答2:
I highly doubt that this is possible. Not only would one be able to interfere normal program behaviour (say, F5 to refresh the page, or ALT+F4 to close the browser), but in a quick test it looks like for keys like F1 etc. no event is fired, so there is no way for a input to receive that.
来源:https://stackoverflow.com/questions/4907114/suppressing-keypress-for-non-character-keys