在没有实际按键的情况下调用KeyPress事件 [英] Invoking KeyPress Event Without Actually Pressing Key
问题描述
只是想知道。是否可以在JavaScript中调用按键事件而无需按键?例如,我可以说,我的网页上有一个按钮,当点击该按钮时,我想调用一个事件,好像按下了某个特定的按键一样。我知道这很奇怪,但可以用JavaScript完成。
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.
推荐答案
是的,这可以使用 initKeyEvent 。但是,使用它有点冗长。如果这让您感到困扰,请使用jQuery,如 @WojtekT 的回答所示。
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.
否则,在vanilla javascript中,这就是它的工作原理:
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 );
这篇关于在没有实际按键的情况下调用KeyPress事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!