按键和按下时的String.fromCharCode返回错误的字符 [英] String.fromCharCode on keypress and keydown are returning wrong characters

查看:323
本文介绍了按键和按下时的String.fromCharCode返回错误的字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图捕获在屏幕上显示之前插入的字符以验证屏幕.看看我的代码

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

例如,如果我键入~或任何其他标点字符,它将返回非拉丁字符,例如å.我正在使用Ubuntu的Chromium.

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

我注意到按键被这些特殊字符所忽略,这是一种耻辱,这就是为什么我也尝试按键.但是keydown无法检测到正确的字符并将其转换为斯堪的纳维亚和亚洲字符.

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?

推荐答案

请参见对类似问题的这个绝妙答案,以及相关的jsfiddle: http://jsfiddle.net/S2dyB/17/

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

一个问题是keypresskeydown事件不可互换. keypress用于检索键入的实际字符(因此将忽略特殊键),而keydown返回键盘上每个键的唯一字符代码.更为严重的是,不同的浏览器对每个事件的处理方式略有不同,从而使事情变得一团糟.

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.

看看e.whichkeydownkeypress之间如何变化: http://jsfiddle. net/9TyzP/

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

如您所见,它们很少匹配-并且具有许多键,keypress的显示代码完全不变,表明该键没有触发该事件.

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.

这篇关于按键和按下时的String.fromCharCode返回错误的字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆