提问人:ShamilS 提问时间:5/12/2023 更新时间:5/12/2023 访问量:142
使用 Javascript 将键盘输入模拟为 <input> HTML 元素
Using Javascript to simulate keyboard input into an <input> HTML element
问:
这是 Javascript 代码:
function getKeyBoardEvent(c, eventName = "keydown") {
return new KeyboardEvent(eventName, {
altKey:false,
bubbles: true,
cancelBubble: false,
cancelable: true,
charCode: 0,
code: "Key" + c.toUpperCase(),
composed: true,
ctrlKey: false,
currentTarget: null,
defaultPrevented: true,
detail: 0,
eventPhase: 0,
isComposing: false,
isTrusted: true,
key: c,
keyCode: c.toUpperCase().charCodeAt(0),
location: 0,
metaKey: false,
repeat: false,
returnValue: false,
shiftKey: false,
type: eventName,
which: c.toUpperCase().charCodeAt(0)});
}
function typeWord(control, word) {
for (let i = 0; i < word.length; i++) {
const char = word.charAt(i);
var event = getKeyBoardEvent(word.charAt(i), "keydown");
control.dispatchEvent(event);
}
}
var id = "testId";
var input = document.getElementById(id);
// console.log(input)
typeWord(input, "Hello, World!")
它不会导致任何文本“键入”到 HTML 元素中。这个代码有什么问题?(元素选择正确,已通过注释代码行进行了测试。console.log(input)
以下模拟密钥的代码效果很好:Enter
var evt = new KeyboardEvent('keydown', {altKey:false,
bubbles: true,
cancelBubble: false,
cancelable: true,
charCode: 0,
code: "Enter",
composed: true,
ctrlKey: false,
currentTarget: null,
defaultPrevented: true,
detail: 0,
eventPhase: 0,
isComposing: false,
isTrusted: true,
key: "Enter",
keyCode: 13,
location: 0,
metaKey: false,
repeat: false,
returnValue: false,
shiftKey: false,
type: "keydown",
which: 13});
var id = "testId";
var input = document.getElementById(id);
input.dispatchEvent(evt);
答: 暂无答案
评论
keydown
input
input