Invoking KeyPress Event Without Actually Pressing Key

倾然丶 夕夏残阳落幕 提交于 2019-12-19 02:54:16

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!