确定JavaScript e.keyCode是否是可打印(非控制)字符 [英] Determine if JavaScript e.keyCode is a printable (non-control) character
问题描述
我只想知道与可输入字符对应的JavaScript keyCode
的范围;或者,不可输入(控制)字符的范围,如退格,转义,命令,移位等,所以我可以忽略它们。
I'd just like to know the range(s) of JavaScript keyCode
s that correspond to typeable characters; or alternatively, the range of non-typeable (control) characters like backspace, escape, command, shift, etc. so I can ignore them.
我问的原因是调用 String.fromCharCode()
会导致控制键出现奇数字符。例如,左侧命令为[,左箭头为%。很奇怪。
The reason I ask is calling String.fromCharCode()
is resulting in odd characters for control keys. For example I get "[" for left command, "%" for left arrow. Weirdness like that.
推荐答案
Keydown将为您提供按下的键的keyCode,无需任何修改。
Keydown will give you the keyCode of the key pressed, without any modifications.
$("#keypresser").keydown(function(e){
var keycode = e.keyCode;
var valid =
(keycode > 47 && keycode < 58) || // number keys
keycode == 32 || keycode == 13 || // spacebar & return key(s) (if you want to allow carriage returns)
(keycode > 64 && keycode < 91) || // letter keys
(keycode > 95 && keycode < 112) || // numpad keys
(keycode > 185 && keycode < 193) || // ;=,-./` (in order)
(keycode > 218 && keycode < 223); // [\]' (in order)
return valid;
});
只有数字键,字母键和空格键才会有与相关的密码代码String.fromCharCode
因为它使用Unicode值。
Only the number keys, letter keys, and spacebar will have keycodes correlating to String.fromCharCode
as it uses Unicode values.
Keypress将是输入文本的charCode表示。请注意,如果由于按键没有打印文本,则不会触发此事件。
Keypress will be the charCode representation of the text entered. Note that this event won't fire if no text is "printed" as a result of the keypress.
$("#keypresser").keypress(function(e){
var charcode = e.charCode;
var char = String.fromCharCode(charcode);
console.log(char);
});
http://jsfiddle.net/LZs2D/1/ 将演示这些如何工作。
http://jsfiddle.net/LZs2D/1/ Will demonstrate how these work.
KeyUp的行为与KeyDown类似。
KeyUp behaves similarly to KeyDown.
这篇关于确定JavaScript e.keyCode是否是可打印(非控制)字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!