是否可以在JavaScript中以编程方式模拟按键事件?
当前回答
截至2019年,这个解决方案对我来说是有效的:
document.dispatchEvent(
new KeyboardEvent("keydown", {
key: "e",
keyCode: 69, // example values.
code: "KeyE", // put everything you need in this object.
which: 69,
shiftKey: false, // you don't need to include values
ctrlKey: false, // if you aren't going to use them.
metaKey: false // these are here for example's sake.
})
);
为了支持带有模拟键盘的移动设备,我在自己的浏览器游戏中使用了这种方法。
澄清:这段代码分派一个keydown事件,而真正的按键将触发一个keydown事件(如果按住时间较长,则会触发多个keydown事件),然后在释放该键时触发一个keyup事件。如果您也需要keyup事件,也可以通过在代码片段中将“keydown”更改为“keyup”来模拟keyup事件。
这也会将事件发送到整个网页,也就是文档。如果只希望特定元素接收事件,可以用document代替所需元素。
其他回答
下面是一个在Chrome和Chromium上工作的解决方案(只测试了这些平台)。似乎Chrome有一些错误或自己的方法来处理关键代码,所以这个属性必须单独添加到KeyboardEvent。
函数simulateKeydown (keycode, istrl,isAlt,isShift){ var e = new KeyboardEvent("keydown",{冒泡泡:true, cancelable:true, char:String.fromCharCode(keycode), key:String.fromCharCode(keycode), shiftKey:isShift, ctrlKey:isCtrl, altKey:isAlt}); Object.defineProperty(e, 'keyCode', {get: function(){返回this.keyCodeVal;}}); e.keyCodeVal = keycode; document.dispatchEvent (e); } simulateKeydown(39, false, false, false);
这种方法支持跨浏览器更改键代码的值。 源
var $textBox = $("#myTextBox");
var press = jQuery.Event("keypress");
press.altGraphKey = false;
press.altKey = false;
press.bubbles = true;
press.cancelBubble = false;
press.cancelable = true;
press.charCode = 13;
press.clipboardData = undefined;
press.ctrlKey = false;
press.currentTarget = $textBox[0];
press.defaultPrevented = false;
press.detail = 0;
press.eventPhase = 2;
press.keyCode = 13;
press.keyIdentifier = "";
press.keyLocation = 0;
press.layerX = 0;
press.layerY = 0;
press.metaKey = false;
press.pageX = 0;
press.pageY = 0;
press.returnValue = true;
press.shiftKey = false;
press.srcElement = $textBox[0];
press.target = $textBox[0];
press.type = "keypress";
press.view = Window;
press.which = 13;
$textBox.trigger(press);
一个非jquery版本,工作在webkit和gecko:
var keyboardEvent = document.createEvent('KeyboardEvent'); var initMethod = typeof keyboardEvent.initKeyboardEvent !== 'undefined' ? 'initKeyboardEvent' : 'initKeyEvent'; keyboardEvent[initMethod]( 'keydown', // event type: keydown, keyup, keypress true, // bubbles true, // cancelable window, // view: should be window false, // ctrlKey false, // altKey false, // shiftKey false, // metaKey 40, // keyCode: unsigned long - the virtual key code, else 0 0, // charCode: unsigned long - the Unicode character associated with the depressed key, else 0 ); document.dispatchEvent(keyboardEvent);
让它工作的关键部分是认识到charCode, keyCode和这些都是不推荐的方法。因此,如果处理按键事件的代码使用这三个中的任何一个,那么它将收到一个伪答案(例如,默认值为0)。
只要使用非弃用的方法(如key)访问按键事件,就应该没问题。
为了完成,我添加了触发事件的基本Javascript代码:
const rightArrowKey = 39 const event = new KeyboardEvent('keydown',{'key':rightArrowKey}) document.dispatchEvent(事件)
基于@aljgom的回答:
这对我来说很有效。而不是像aljgom建议的那样将事件分派给元素,而是将它分派给文档。
document.dispatchEvent(new KeyboardEvent("keydown", { key: "c" }));