I'm trying to send characters to an input element based on user actions.
(我正在尝试根据用户操作将字符发送到输入元素。)
I'm trying to use KeyboardEvent
with dispatchEvent
but whatever I do, it doesn't work
(我正在尝试将KeyboardEvent
与dispatchEvent
一起使用,但是无论我做什么,它都无法正常工作)
For example:
(例如:)
let keyEvent = new KeyboardEvent();
keyEvent.key = 'a';
keyEvent.keyCode = 'a'.charCodeAt(0);
keyEvent.which = event['keyCode'];
keyEvent.altKey = false;
keyEvent.ctrlKey = true;
keyEvent.shiftKey = false;
keyEvent.metaKey = false;
keyEvent.bubbles = true;
Not sure if this is correct, but I have dispatched it as follows:
(不知道这是否正确,但是我已按如下方式调度它:)
document.querySelector('input').dispatchEvent(keyEvent);
document.activeElement.dispatchEvent(keyEvent);
document.dispatchEvent(keyEvent);
DEMO
(演示)
If I first focus the input before clicking the button nothing really happens.
(如果我在单击按钮之前先关注输入内容,则什么也没有发生。)
Any suggestions what might go wrong here ?(有什么建议可能会出什么问题吗?)
ask by Jeanluca Scaljeri translate from so
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…