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

别等时光非礼了梦想. 提交于 2019-11-28 01:04:53

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.

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.

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.selectionStart gives the starting position of the text you have selected and srcField.selectionEnd gives the end position of the selection, if you haven't selected any text srcField.selectionStart equals srcField.selectionEnd.

The function setCaretPosition came from this answer by kd7. I only changed it to make it receive the element instead of its 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();
        }
    }
}

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.

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