Home >Web Front-end >JS Tutorial >How to Correctly Specify Keycodes for Keydown Simulations in Chrome?
To simulate keydown events on a given textarea element in Chrome, you should utilize the initKeyboardEvent method. However, the initial code you provided received a different result - the Enter keycode, instead of the intended m keycode.
To correct this, you need to override both the keyCode and which properties of the KeyboardEvent object. Here's the updated code:
<code class="javascript">var keyEvent = document.createEvent('KeyboardEvent'); // Override both keyCode and which Object.defineProperty(keyEvent, 'keyCode', { get: function() { return this.keyCodeVal; } }); Object.defineProperty(keyEvent, 'which', { get: function() { return this.keyCodeVal; } }); keyEvent.initKeyboardEvent('keydown', true, false, null, 0, false, 0, false, 77, 0); keyEvent.keyCodeVal = 77; inputNode.dispatchEvent(keyEvent);</code>
By overriding both properties, you ensure that the browser receives the correct keycode value. This solution effectively simulates the keydown event for the specified key, allowing you to achieve the desired functionality.
The above is the detailed content of How to Correctly Specify Keycodes for Keydown Simulations in Chrome?. For more information, please follow other related articles on the PHP Chinese website!