Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
444 views
in Technique[技术] by (71.8m points)

javascript - How to catch event.keyCode and change it to another 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.

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

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...