Javascript 如何捕获 event.keyCode 并将其更改为另一个 keyCode?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8776543/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 07:28:40  来源:igfitidea点击:

How to catch event.keyCode and change it to another keyCode?

javascriptjquerykeycode

提问by Eye

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.

我在 SO 上检查了其他问题,但是他们没有回答我的问题。我想简单地捕获某些 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.

下面是我的代码。但是你可以用你的(例如,当按下大写的“A”时,它应该用零替换 0 等)替换这些 keyCodes。这个想法是替换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?

我也尝试过 keydown 和 keyup。它们不会更改 keyCode。我怎样才能做到这一点?

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.

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

回答by Selvakumar Arumugam

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

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

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

请参阅 MDN 中的参考 -键盘事件- 无法设置所有只读。

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.

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

回答by MauricioJuanes

I am using the following code to achieve the same result as if I had changed the keyCode, without actually being able to change it.

我正在使用以下代码实现与更改 相同的结果keyCode,但实际上无法更改它。

function inputValidation() {
    var srcField = event.srcElement;
    var sKey = event.keyCode;
    var inputLetter = String.fromCharCode(sKey);
    if (typeof(srcField) !== "undefined" && srcField !== null) {
        inputLetter = transformInput(inputLetter);
        var caretPos = srcField.selectionStart;
        var startString = srcField.value.slice(0, srcField.selectionStart);
        var endString = srcField.value.slice(srcField.selectionEnd, srcField.value.length);
        srcField.value = startString + inputLetter + endString;
        setCaretPosition(srcField, caretPos+1); // '+1' puts the caret after the input
        event.preventDefault ? event.preventDefault() : event.returnValue = false; //for IE8
   }
}

srcField.selectionStartgives the starting position of the text you have selected and srcField.selectionEndgives the end position of the selection, if you haven't selected any text srcField.selectionStartequals srcField.selectionEnd.

srcField.selectionStart给出您选择的文本的起始位置并srcField.selectionEnd给出选择的结束位置,如果您没有选择任何文本srcField.selectionStartequals srcField.selectionEnd

The function setCaretPositioncame from this answerby kd7. I only changed it to make it receive the element instead of its Id

该功能setCaretPosition来自kd7 的这个答案。我只是改变它以使其接收元素而不是它的 Id

function setCaretPosition(elem, caretPos) {
    if (elem != null) {
        if (elem.createTextRange) {
            var range = elem.createTextRange();
            range.move('character', caretPos);
            range.select();
        } else {
            if (elem.selectionStart) {
                elem.focus();
                elem.setSelectionRange(caretPos, caretPos);
            } else
                elem.focus();
        }
    }
}

回答by Sean256

While the properties on the KeyboardEvent instance is READ ONLY, you can override KeyboardEvent's prototype and create a getter for whatever you want to change. Here is an example which changes the keycodes of hjkl to act like arrow keys.

虽然 KeyboardEvent 实例上的属性是只读的,但您可以覆盖KeyboardEvent的原型并为您想要更改的任何内容创建一个 getter。这是一个将 hjkl 的键码更改为箭头键的示例。

Object.defineProperty(KeyboardEvent.prototype, 'keyCode', {
    get: function() {
        switch (this.key) {
            case 'h': return 37; // left
            case 'j': return 40; // down
            case 'k': return 38; // up
            case 'l': return 39; // right
            default: return this.which
        }
    }
})

回答by burak

you can change value as manuel and handle keypress. if you want to check key declare a variable and check your keycode.

您可以将值更改为 manuel 并处理按键操作。如果你想检查键声明一个变量并检查你的键码。

this.event.target.value = this.event.target.value + ".";
return false;

full code:

完整代码:

function isNumberKeyDec(evt) {
    var charCode = (evt.which) ? evt.which : event.keyCode;
    var apos = 0;
    if (charCode == 44) {
        apos = 1;
        charCode = 46;
    }
    if (this.event.target.value.length == 0 && charCode == 46) {
        return false;
    }
    if (this.event.target.value.length == 1 && this.event.target.value == "0" && charCode == 48) {
        return false;
    }
    if (this.event.target.value.length == 1 && this.event.target.value == "0" && charCode != 46) {
        this.event.target.value = "";
    }    
    if (charCode > 31 && (charCode < 48 || charCode > 57) && charCode != 46) {

        return false;
    }
    if (charCode == 46 && this.event.target.value.indexOf(".") != -1) {
        return false;
    }
    if (this.event.target.value.indexOf(".") != -1) {
        if (this.event.target.value.substring(this.event.target.value.toString().indexOf(".")).length >= 2) {
            return false;
        }        
    }
    if (this.event.target.value.indexOf(".") == -1 && charCode != 46) {
        if (this.event.target.value.length >= 3 && charCode != 46) {
            return false;
        }
    }
    if (apos == 1) {
        this.event.target.value = this.event.target.value + ".";
        return false;
    }
    return true;
}