只是想知道。是否可以在 JavaScript 中调用按键事件而无需实际按下按键?例如,我的网页上有一个按钮,当单击该按钮时,我想调用一个事件,就好像按下了一个特定的键一样。我知道这很奇怪,但这可以用 JavaScript 完成吗?
最佳答案
是的,这可以使用 initKeyEvent 来完成.不过,使用起来有点冗长。如果这让您感到困扰,请使用 jQuery,如 @WojtekT 中所示。的答案。
否则,在 vanilla javascript 中,它是这样工作的:
// 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 );
关于javascript - 调用 KeyPress 事件而不实际按下键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10514123/