问题
Just wondering. Is it possible to invoke a key press event in JavaScript without ACTUALLY pressing the key ? For example lets say, I have a button on my webpage and when that button is clicked I want to invoke a event as if a particular key has been pressed. I know it weird but can this be done in JavaScript.
回答1:
Yes, this can be done using initKeyEvent. It's a little verbose to use, though. If that bothers you, use jQuery, as shown in @WojtekT's answer.
Otherwise, in vanilla javascript, this is how it works:
// Create the event
var evt = document.createEvent( 'KeyboardEvent' );
// Init the options
evt.initKeyEvent(
"keypress", // the kind of event
true, // boolean "can it bubble?"
true, // boolean "can it be cancelled?"
null, // specifies the view context (usually window or null)
false, // boolean "Ctrl key?"
false, // boolean "Alt key?"
false, // Boolean "Shift key?"
false, // Boolean "Meta key?"
9, // the keyCode
0); // the charCode
// Dispatch the event on the element
el.dispatchEvent( evt );
回答2:
If you're using jquery:
var e = jQuery.Event("keydown");
e.which = 50; //key code
$("#some_element").trigger(e);
来源:https://stackoverflow.com/questions/10514123/invoking-keypress-event-without-actually-pressing-key