使用 Javascript 将键盘输入模拟为 <input> HTML 元素

Using Javascript to simulate keyboard input into an <input> HTML element

提问人:ShamilS 提问时间:5/12/2023 更新时间:5/12/2023 访问量:142

问:

这是 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);
JavaScript 模拟 键盘事件

评论

0赞 ShamilS 5/13/2023
@Yogi:是的,看起来无法模拟/调度 HTML 元素的事件。在我的情况下,使用 JavaScript 设置元素的 value 属性无济于事。keydowninputinput

答: 暂无答案