7

就是想。是否可以在不实际按下键的情况下在 JavaScript 中调用按键事件?例如,假设我的网页上有一个按钮,当单击该按钮时,我想调用一个事件,就好像按下了一个特定的键一样。我知道这很奇怪,但这可以在 JavaScript 中完成。

4

2 回答 2

5

是的,这可以使用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 );
于 2012-05-09T10:41:22.457 回答
3

如果您使用的是 jquery:

var e = jQuery.Event("keydown");
e.which = 50; //key code
$("#some_element").trigger(e);
于 2012-05-09T10:21:27.270 回答