在没有实际按下键的情况下调用KeyPress事件

sko*_*kos 6 javascript keypress

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

Flo*_*ine 5

是的,这可以使用initKeyEvent完成。不过,它有点冗长。如果那样困扰您,请使用jQuery,如@WojtekT的答案所示。

否则,在普通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 );
Run Code Online (Sandbox Code Playgroud)


Woj*_*ekT 3

如果您使用 jquery:

var e = jQuery.Event("keydown");
e.which = 50; //key code
$("#some_element").trigger(e);
Run Code Online (Sandbox Code Playgroud)