Issue with ascii keycode in javascript
我在javascript中看到了一个奇怪的问题,或者可能是因为javascript对我来说是新的。
我试图在onkeypress上允许某些操作,但是仅在按下字母数字或特殊字符时才允许。 这是我的代码:
1 2 3 | if(e.keyCode>=32 && e.keyCode<=126 ){ alert(e.keyCode);} } |
如果我按下任何特殊字符键(如
您需要在大多数浏览器中使用
这是我最喜欢的东西参考:http://unixpapa.com/js/key.html
1 2 3 4 5 6 7 | document.onkeypress = function(e) { e = e || window.event; var charCode = (typeof e.which =="number") ? e.which : e.keyCode; var charTyped = String.fromCharCode(charCode); alert("Character typed:" + charTyped); }; |
您已假定
MDN说:
In a
keypress event, the Unicode value of the key pressed is stored in either thekeyCode orcharCode property, never both. If the key pressed generates a character (e.g. 'a'),charCode is set to the code of that character, respecting the letter case. (i.e.charCode takes into account whether the shift key is held down). Otherwise, the code of the pressed key is stored inkeyCode .
keyCode is always set in the keydown and keyup events. In these cases, charCode is never set.To get the code of the key regardless of whether it was stored in
keyCode orcharCode , query the which property.For a list of the keyCode values associated with particular keys, run the example in Example 7: Displaying Event Object Constants and view the resulting HTML table.
如指示进行操作,则表明您的某些"特殊"字符超出了您指定的范围限制。
凯文(Kevin)也指出了这个有用的表格,但是最好使用更规范的方法来处理按键。
逗号(
http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes
您应该使用
尝试这个:
1 2 3 4 5 6 7 | document.onkeypress = function(e) { console.log(e.keyCode +" --" + e.which +" --" + e.charCode); if(e.which >= 32 && e.which <= 126 ){ alert(e.which); } }; |