是否可以在JavaScript中以编程方式模拟按键事件?
当前回答
我想模拟按Tab键……扩展Trevor的回答,我们可以看到像“tab”这样的特殊键确实会被按下,但我们看不到按“tab”会产生的实际结果……
尝试与调度这些事件的'activeElement'以及全局文档对象都-代码添加下面;
代码片段如下:
var element = document.getElementById("firstInput"); document.addEventListener("keydown", function(event) { console.log('we got key:', event.key, ' keyCode:', event.keyCode, ' charCode:', event.charCode); /* enter is pressed */ if (event.keyCode == 13) { console.log('enter pressed:', event); theKey = 'Tab'; attributes = { bubbles: true, key: theKey, keyCode: 9, charCode: 0, }; setTimeout(function() { /* event.keyCode = 13; event.target.value += 'b'; */ var e = new window.KeyboardEvent('focus', attributes); document.activeElement.dispatchEvent(e); e = new window.KeyboardEvent('keydown', attributes); document.activeElement.dispatchEvent(e); e = new window.KeyboardEvent('beforeinput', attributes); document.activeElement.dispatchEvent(e); e = new window.KeyboardEvent('keypress', attributes); document.activeElement.dispatchEvent(e); e = new window.KeyboardEvent('input', attributes); document.activeElement.dispatchEvent(e); e = new window.KeyboardEvent('change', attributes); document.activeElement.dispatchEvent(e); e = new window.KeyboardEvent('keyup', attributes); document.activeElement.dispatchEvent(e); }, 4); setTimeout(function() { var e = new window.KeyboardEvent('focus', attributes); document.dispatchEvent(e); e = new window.KeyboardEvent('keydown', attributes); document.dispatchEvent(e); e = new window.KeyboardEvent('beforeinput', attributes); document.dispatchEvent(e); e = new window.KeyboardEvent('keypress', attributes); document.dispatchEvent(e); e = new window.KeyboardEvent('input', attributes); document.dispatchEvent(e); e = new window.KeyboardEvent('change', attributes); document.dispatchEvent(e); e = new window.KeyboardEvent('keyup', attributes); document.dispatchEvent(e); }, 100); } else if (event.keyCode != 0) { console.log('we got a non-enter press...: :', event.key, ' keyCode:', event.keyCode, ' charCode:', event.charCode); } }); <h2>convert each enter to a tab in JavaScript... check console for output</h2> <h3>we dispatchEvents on the activeElement... and the global element as well</h3> <input type='text' id='firstInput' /> <input type='text' id='secondInput' /> <button type="button" onclick="document.getElementById('demo').innerHTML = Date()"> Click me to display Date and Time.</button> <p id="demo"></p>
其他回答
在某些情况下,按键事件不能提供所需的功能。从mozilla文档中我们可以看到该特性已被弃用:
不再推荐使用此特性。虽然一些浏览器可能仍然支持它,但它可能已经从相关的网络标准中删除了,可能正在被删除的过程中,或者可能只是为了兼容性的目的而保留。避免使用它,并尽可能更新现有代码;请参阅本页底部的兼容性表,以指导您的决定。请注意,此功能可能在任何时候停止工作。
因此,由于按键事件是由两个随后触发的事件keydown和接下来的同一个按键的keyup组合而成的,只需一个接一个地生成事件:
element.dispatchEvent(new KeyboardEvent('keydown',{'key':'Shift'}));
element.dispatchEvent(new KeyboardEvent('keyup',{'key':'Shift'}));
这里有一个真正有用的库:https://cdn.rawgit.com/ccampbell/mousetrap/2e5c2a8adbe80a89050aaf4e02c45f02f1cc12d4/tests/libs/key-event.js
我不知道它是从哪里来的,但它是有帮助的。它向window添加了一个.simulate()方法。你可以简单地用KeyEvent。simulate(0,13)用于模拟enter或KeyEvent。为'Q'模拟(81,81)。
我在https://github.com/ccampbell/mousetrap/tree/master/tests上买的。
截至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代替所需元素。
我知道这个问题要求一个javascript的方式来模拟一个按键。但是对于那些正在寻找jQuery方法的人来说:
var e = jQuery.Event("keypress");
e.which = 13 //or e.keyCode = 13 that simulates an <ENTER>
$("#element_id").trigger(e);
一个非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);
推荐文章
- ReactJS和公共文件夹中的图像
- 在React Native中使用Fetch授权头
- 为什么我的球(物体)没有缩小/消失?
- 如何使用jQuery检测页面的滚动位置
- if(key in object)或者if(object. hasownproperty (key)
- 一元加/数字(x)和parseFloat(x)之间的区别是什么?
- angularjs中的compile函数和link函数有什么区别
- 删除绑定中添加的事件监听器
- 很好的初学者教程socket.io?
- HtmlSpecialChars在JavaScript中等价于什么?
- React: 'Redirect'没有从' React -router-dom'中导出
- 如何在React中使用钩子强制组件重新渲染?
- 我如何使用Jest模拟JavaScript的“窗口”对象?
- 我如何等待一个承诺完成之前返回一个函数的变量?
- 在JavaScript中根据键值查找和删除数组中的对象