javascript中的ascii键码问题

Issue with ascii keycode in javascript

我在javascript中看到了一个奇怪的问题,或者可能是因为javascript对我来说是新的。

我试图在onkeypress上允许某些操作,但是仅在按下字母数字或特殊字符时才允许。 这是我的代码:

1
2
3
if(e.keyCode>=32 && e.keyCode<=126 ){
    alert(e.keyCode);}
}

如果我按下任何特殊字符键(如{,]>.),它不会发出警报,我是否在这里缺少任何内容?


您需要在大多数浏览器中使用which属性,而仅在IE中使用keyCode。您确实有正确的事件:如果您对键入的字符而不是按下的物理键感兴趣,则只有keypress会起作用。

这是我最喜欢的东西参考: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);
};


您已假定keyCode为您提供了ASCII索引,但这是不正确的。由于这种假设,您的范围标准不正确。

MDN说:

In a keypress event, the Unicode value of the key pressed is stored in either the keyCode or charCode 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 in keyCode.

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 or charCode, 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)也指出了这个有用的表格,但是最好使用更规范的方法来处理按键。


逗号(,)的keyCode是188。这可能是为什么吗?

http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes


您应该使用which,它应该在Firefox和Chrome中都可以使用。

尝试这个:

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);
    }
};