是否可以在JavaScript中以编程方式模拟按键事件?
当前回答
一个非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);
其他回答
只要用户按下有问题的键,你就可以存储对该even的引用,并将其用于任何HTML其他元素:
EnterKeyPressToEmulate<input class="lineEditInput" id="addr333_1" type="text" style="width:60%;right:0%;float:right" onkeydown="keyPressRecorder(event)"></input> TypeHereToEmulateKeyPress<input class="lineEditInput" id="addr333_2" type="text" style="width:60%;right:0%;float:right" onkeydown="triggerKeyPressOnNextSiblingFromWithinKeyPress(event)"> Itappears Here Too<input class="lineEditInput" id="addr333_3" type="text" style="width:60%;right:0%;float:right;" onkeydown="keyPressHandler(event)"> <script> var gZeroEvent; function keyPressRecorder(e) { gZeroEvent = e; } function triggerKeyPressOnNextSiblingFromWithinKeyPress(TTT) { if(typeof(gZeroEvent) != 'undefined') { TTT.currentTarget.nextElementSibling.dispatchEvent(gZeroEvent); keyPressHandler(TTT); } } function keyPressHandler(TTT) { if(typeof(gZeroEvent) != 'undefined') { TTT.currentTarget.value+= gZeroEvent.key; event.preventDefault(); event.stopPropagation(); } } </script>
如果你创建自己的事件,你可以设置keyCode,你可以从任何真实的键盘事件复制现有的参数(忽略目标,因为它的工作dispatchEvent)和:
ta = new KeyboardEvent('keypress',{ctrlKey:true,key:'Escape'})
如果你可以使用jQuery 1.3.1:
函数simulateKeyPress(字符){ jQuery.event.trigger ({ 类型:键盘按键, 其中:character.charCodeAt (0) }); } $(函数(){ 美元(的身体).keypress(函数(e) { 警报(e.which); }); simulateKeyPress(“e”); }); < script src = " https://cdnjs.cloudflare.com/ajax/libs/jquery/1.3.1/jquery.min.js " > > < /脚本
你可以使用dispatchEvent():
function simulateKeyPress() {
var evt = document.createEvent("KeyboardEvent");
evt.initKeyboardEvent("keypress", true, true, window,
0, 0, 0, 0,
0, "e".charCodeAt(0))
var body = document.body;
var canceled = !body.dispatchEvent(evt);
if(canceled) {
// A handler called preventDefault
alert("canceled");
} else {
// None of the handlers called preventDefault
alert("not canceled");
}
}
我没有对此进行测试,但它改编自dispatchEvent()文档中的代码。您可能需要通读这些文档,以及createEvent()和initKeyEvent()的文档。
你可以在EventTarget(元素,窗口,文档等)上分派键盘事件,如下所示:
element.dispatchEvent(new KeyboardEvent('keydown', {'key': 'a'}));
但是,dispatchEvent可能不会更新输入字段值,也可能不会触发常规键盘按下的行为,这可能是因为Event的原因。itrusted property,我不知道是否有办法绕过
但是你也可以通过设置输入值来改变输入。
element.value += "a";
例子:
let element = document.querySelector('input'); 元素。Onkeydown = e =>警报(e.key); changeValButton。Onclick =() =>元素。Value += "a"; dispatchButton。Onclick = () => { 元素。dispatchEvent(new KeyboardEvent('keydown', {'key': 'a'})); } <输入/ > <button id="dispatchButton">按下分派事件</button> <button id="changeValButton">按下按钮更改值</button> . </button id="changeValButton">
您可以根据需要向事件添加更多属性,如本答案所示。看一下KeyboardEvent文档
element.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.
}));
此外,由于keypress已弃用,您可以使用keydown + keyup,例如:
element.dispatchEvent(new KeyboardEvent('keydown', {'key':'Shift'} ));
element.dispatchEvent(new KeyboardEvent( 'keyup' , {'key':'Shift'} ));
对于使用ReactJS的页面,这是一个尝试模拟键盘行为的线程
这就是我在chrome中使用js/typescript所做的尝试。多亏了 这是灵感的答案。
var x = document.querySelector('input');
var keyboardEvent = new KeyboardEvent("keypress", { bubbles: true });
// you can try charCode or keyCode but they are deprecated
Object.defineProperty(keyboardEvent, "key", {
get() {
return "Enter";
},
});
x.dispatchEvent(keyboardEvent);
{ // example document.querySelector('input').addEventListener("keypress", e => console.log("keypress", e.key)) // unfortunatelly doesn't trigger submit document.querySelector('form').addEventListener("submit", e => { e.preventDefault(); console.log("submit") }) } var x = document.querySelector('input'); var keyboardEvent = new KeyboardEvent("keypress", { bubbles: true }); // you can try charCode or keyCode but they are deprecated Object.defineProperty(keyboardEvent, "key", { get() { return "Enter"; }, }); x.dispatchEvent(keyboardEvent); <form> <input> </form>
推荐文章
- 克隆对象没有引用javascript
- 验证字符串是否为正整数
- 如何获得一个键/值JavaScript对象的键
- 什么时候JavaScript是同步的?
- 如何在Typescript中解析JSON字符串
- Javascript reduce()在对象
- 在angularJS中& vs @和=的区别是什么
- 错误"Uncaught SyntaxError:意外的标记与JSON.parse"
- JavaScript中的querySelector和querySelectorAll vs getElementsByClassName和getElementById
- 给一个数字加上st, nd, rd和th(序数)后缀
- 如何以编程方式触发引导模式?
- setTimeout带引号和不带括号的区别
- 在JS的Chrome CPU配置文件中,'self'和'total'之间的差异
- 用javascript检查输入字符串中是否包含数字
- 如何使用JavaScript分割逗号分隔字符串?