如何用Javascript模拟输入框中的键入?

Mar*_*rty 5 html javascript css

我想做的是使输入框认为我在其中输入数字,而不是更改所述输入的值。因此,我要做的第一件事是使输入框成为变量:

var input = document.querySelectorAll("input")[1];
Run Code Online (Sandbox Code Playgroud)

然后,我要做的就是聚焦输入框,使其看起来就像我用鼠标单击它一样:

input.select();
Run Code Online (Sandbox Code Playgroud)

这是我现在停留的部分。我想做的就是让输入框认为我在其中输入了数字,例如41。 , 这将不胜感激。谢谢。

小智 14

我知道这确实是很久以前的事了,但我目前正在解决一个非常相似的问题,并且遇到了与原始海报所遇到的完全相同的问题,我发现了这个代码片段(信用):

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.
}));
Run Code Online (Sandbox Code Playgroud)

您需要的具体密钥代码可以在这里找到。

这绝对是一种极其复杂的做事方式,您需要一些东西来将您拥有的任何输入字符串转换为 KeyboardEvent 实例的列表,然后一个接一个地分派它们,但据我所知,这是正确的真正“模拟”键盘输入的方法。


Tem*_*fif 5

您可以setTimeout每次使用和添加一个字符,如下所示:

var input = document.querySelectorAll("input")[1];
input.select(); // you can also use input.focus()
input.value="";

var text = "41";
var l=text.length;
var current = 0;
var time = 1000;


var write_text = function() {
  input.value+=text[current];
  if(current < l-1) {
    current++;
    setTimeout(function(){write_text()},time);
  } else {
    input.setAttribute('value',input.value);
  }
}
setTimeout(function(){write_text()},time);
Run Code Online (Sandbox Code Playgroud)
<input type="text">
<input type="text">
Run Code Online (Sandbox Code Playgroud)

这将与您要编写的任何内容一起使用,您只需要根据需要调整变量即可。