是否可以以编程方式模拟按键事件?
2022-08-29 23:03:56
是否可以在 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);
您可以在 EventTarget(元素、窗口、文档等)上调度键盘事件,如下所示:
element.dispatchEvent(new KeyboardEvent('keydown', {'key': 'a'}));
但是,可能不会更新输入字段值,并且可能不会触发常规键盘按下所具有的行为,这可能是因为 Event.isTrusted 属性,我不知道是否有办法绕过该属性dispatchEvent
但是,您也可以通过设置其 .value
element.value += "a";
例:
let element = document.querySelector('input');
element.onkeydown = e => alert(e.key);
changeValButton.onclick = () => element.value += "a";
dispatchButton.onclick = () => {
element.dispatchEvent(new KeyboardEvent('keydown', {'key': 'a'}));
}
<input/>
<button id="dispatchButton">Press to dispatch event </button>
<button id="changeValButton">Press to change value </button>
您可以根据需要向事件添加更多属性,如本答案所示。查看键盘事件文档
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 的页面,这是一个尝试模拟键盘行为的线程