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

前端 未结 4 1807
無奈伤痛
無奈伤痛 2020-12-06 10:56

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 char

4条回答
  •  独厮守ぢ
    2020-12-06 11:33

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

提交回复
热议问题