consistent keyCode for `#`

2019-04-29 09:10发布

While I know that capturing keys due to the e.keyCode vs e.charCode is not trivial, I thought that jQuery would pretty much be able to normalize most of those inconsistencies.

However while answering this question I found out that the character # seems to have very inconsistent keyCodes (and of course this is true for several other codes also, mostly depending on the browser and keyboardlayout I guess).

Chrome and IE yielded 191, Firefox 163 on my computer, another user reported 222. Chromes window.event even reported U+00BF as keyIdentifier - which according to unicode tables should be ¿.

Do you know any consistent way to determine such symbols like the # with inconsistent keyCodes without doing something nasty like the following:

$('input').keydown(function (e) {
        if (e.which == 191 || e.which == 163 || e.which == 222){
            // hope you got the right key
            e.preventDefault();
        }
});

Fiddle for your pleasure.

2条回答
爷、活的狠高调
2楼-- · 2019-04-29 09:15

Have you tried using the keypress event ?

The documentation warns about possible differences in behavior between platforms.

In Firefox at least, e.which corresponds to the ascii code of the typed character after transformation :

$('#txtClient').keypress(function (e) {
    console.log('keypress:', e.which);
    if (e.which == 35) {
        return false;
    }
});

updated fiddle

查看更多
何必那么认真
3楼-- · 2019-04-29 09:20

This works for me in Chrome and Firefox with a US keyboard:

$('[id$=txtClient]').keypress(function (e) {
    if (String.fromCharCode(e.which) == '#') {
        e.preventDefault();
    }
});

keypress is the only event that will give you reliable info on the character that was entered.

Demo: http://jsfiddle.net/elclanrs/ebcet/9/

查看更多
登录 后发表回答