如何捕获event.keyCode并将其更改为另一个keyCode? [英] How to catch event.keyCode and change it to another keyCode?

查看:1036
本文介绍了如何捕获event.keyCode并将其更改为另一个keyCode?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在SO处检查了其他问题,但他们没有回答我的问题。我想简单地捕获某些keyCode并将其替换为另一个。我正在处理字符,而不是空格,我不需要松散焦点等。

I have checked other questions here at SO, however they do not answer my question. I want to simply catch certain keyCode and replace it with another. I am working with characters, not white spaces, and I do not need to loose focus or the like.

以下是我的代码。但是你可以用你的那些替换那些keyCodes(例如,当按下大写A时,它应该替换为零0等)。想法是替换keyCode。

Below is my code. But you can replace those keyCodes with your (eg. when capital "A" is pressed, it should replace with zero 0, etc.). The idea is to replace the keyCode.

phrase.keypress(function(event)
{
    if (event.shiftKey)
    {
        switch (event.keyCode)
        {
            // Cyrillic capitalized "Н" was pressed
            case 1053: event.keyCode = 1187; event.charCode = 1187; event.which = 1187; break;
            // Cyrillic capitalized "О" was pressed
            case 1054: event.keyCode = 1257; event.charCode = 1257; event.which = 1257; break;
            // Cyrillic capitalized "У" was pressed
            case 1059: event.keyCode = 1199; event.charCode = 1199; event.which = 1199; break;
        }
    }
});

我也尝试过keydown和keyup。它们不会改变keyCode。我怎么能这样做?

I tried with keydown and keyup as well. They do not alter the keyCode. How can I do that?

P.S。如果可能的话,我正在寻找一个解决方案,它不会event.preventDefault()并手动将所需的键插入输入字段,然后将光标移动到结尾。我想要更清洁和正确的解决方案。谢谢。

P.S. If possible, I am looking for a solution which does not "event.preventDefault() and manually insert desired key to input field, then move cursor to the end". I want cleaner and "right" solution. Thank you.

推荐答案

键盘事件属性都是只读的。您无法捕获一个keyCode并将其更改为另一个。

Keyboard event properties are all READ-only. You cannot capture one keyCode and change it to another.

请参阅MDN的参考资料 - 键盘事件 - 所有内容都是只读的。

See reference from MDN - Keyboard Events - All are read only can't be set.

正如你在帖子中提到的那样。 - 如果你不想处理,那么你必须停止浏览器默认按键并自己设置所需的元素值。

As you mentioned in your post. -- If you wan't to handle, then you have to stop browser default key press and set the desired value to the element yourself.

这篇关于如何捕获event.keyCode并将其更改为另一个keyCode?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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