我需要检测刚被按下的键是一个可打印的键,如字符,可能有重音,数字,空格,标点符号等,还是不可打印的键,如ENTER,TAB或DELETE.
有没有可靠的方式来做这个Javascript,除了列出所有不可打印的键,希望不要忘记一些?
解决方法
我昨天回答了一个
similar question.请注意,您必须使用按键事件与任何字符相关; keydown不会做.
我会认为Enter是可打印的,顺便说一下,这个功能认为它是.如果您不同意,您可以修改它,以将该事件的哪个或keyCode属性设置为13来过滤掉按键.
- function isCharacterKeyPress(evt) {
- if (typeof evt.which == "undefined") {
- // This is IE,which only fires keypress events for printable keys
- return true;
- } else if (typeof evt.which == "number" && evt.which > 0) {
- // In other browsers except old versions of WebKit,evt.which is
- // only greater than zero if the keypress is a printable key.
- // We need to filter out backspace and ctrl/alt/Meta key combinations
- return !evt.ctrlKey && !evt.MetaKey && !evt.altKey && evt.which != 8;
- }
- return false;
- }
- var input = document.getElementById("your_input_id");
- input.onkeypress = function(evt) {
- evt = evt || window.event;
- if (isCharacterKeyPress(evt)) {
- // Do your stuff here
- alert("Character!");
- }
- });