String.fromCharCode on keypress and keydown are returning wrong characters

泪湿孤枕 提交于 2019-12-10 17:35:13

问题


I'm trying to catch the character inserted before it shows on the screen to validate the screen. See my code

_this.on('keypress keydown',function(e){
    var t = e.target;
    var k = e.which || e.keyCode;
    var c = String.fromCharCode(k);
    console.log(String.fromCharCode(k))
});

If I for example type ~ or any other punctuation characters, it returns non-latin characters, such as å. I'm on Chromium, Ubuntu.

I noticed that the keypress is being ignored with these special characters, what is a shame and that's why I am trying with keydown as well. But keydown fails to detect the right character and converts them to scandinavian and asian characters.

Is there a workaround to get the correct character being yped?


回答1:


See this wonderful answer to a similar question, and the associated jsfiddle: http://jsfiddle.net/S2dyB/17/

One problem is that the keypress and keydown events are not interchangeable. keypress is used to retrieve the actual character that was typed (so special keys are ignored), while keydown returns a unique character code for each key on the keyboard. To exacerbate this, different browsers handle each event a little bit differently, making it a big mess.

Take a look at how e.which varies between keydown and keypress: http://jsfiddle.net/9TyzP/

As you can see, they rarely match up--and with many keys, the displayed code for keypress doesn't change at all, indicating that the event did not fire for that key.



来源:https://stackoverflow.com/questions/31612458/string-fromcharcode-on-keypress-and-keydown-are-returning-wrong-characters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!