【发布时间】:2020-10-28 15:21:43
【问题描述】:
我已阅读并尝试了 this question 的解决方案,但它们都没有按我的预期工作。
在下面的代码 sn-p 中,我注册了两个事件侦听器,并看到两个回调都作为对 input 和 document 上的 keydown 事件的响应而触发。
但是,我的期望是,当这行代码运行时,输入中会输入一个额外的文本,a。
input.dispatchEvent(keyEvent);
换句话说,我希望在 input 元素上以 KeyboardEvent 作为参数调用 dispatchEvent 应该向输入添加文本,但它不会。
它确实调用在 eventListener 中注册的回调。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<input id="input">
<script>
const input = document.getElementById('input')
input.addEventListener('keydown', (e) => {
console.log('Keydown on Input: ', e.key)
})
document.addEventListener('keydown', (e) => {
console.log('Keydown on Doc: ', e.key)
})
function focusInputThenFireEventKeyboardEvents() {
input.value = 'I want '
input.focus()
input.dispatchEvent(new Event('focus'));
input.dispatchEvent(new KeyboardEvent('keypress',{'key':'a'}));
input.dispatchEvent(new KeyboardEvent('keydown',{'key':'a'}));
var keyEvent = new KeyboardEvent("keydown", { key: "a", char: "a", shiftKey: true });
var keyEvent2 = new KeyboardEvent("keydown", { key: "d", char: "d", shiftKey: true });
input.dispatchEvent(keyEvent);
document.dispatchEvent(keyEvent2);
}
setTimeout(focusInputThenFireEventKeyboardEvents, 500)
</script>
</body>
</html>
【问题讨论】:
-
@HassanMonjezi 感谢您的回复。这个没有。 vanilla js 解决方案包括deprecated api keypress 或 jquery。
标签: javascript dom ecmascript-6 dom-events