如何使用Javascript模拟输入框中的键入? [英] How to Simulate Typing in an Input Box with Javascript?

查看:116
本文介绍了如何使用Javascript模拟输入框中的键入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做的是使输入框认为我在其中输入数字,而不是更改所述输入的值.所以我要做的第一件事就是将输入框设置为变量:

What I am trying to do is make the input box think that I am typing numbers into it rather than changing the value of said input. So the first thing I did was make the input box a variable:

var input = document.querySelectorAll("input")[1];

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

Then what I did was focus the input box to make it seem like I had clicked in it with my mouse:

input.select();

这是我现在要坚持的部分.我想做的是让输入框认为我在其中输入了数字,例如41.如果有人可以告诉我,我需要在控制台中输入什么代码,以使输入框认为我输入了"41" , 这将不胜感激.谢谢.

This is the part that I am now stuck on. What I would like to do is make the input box think that I typed a number into it, say, 41. If anyone could please tell me what code I need to put into console to make the input box think I typed in "41", it would be greatly appreciated. Thank you.

推荐答案

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

You can use setTimeout and add one character each time like this :

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);

<input type="text">
<input type="text">

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

This will work with any content you want to write, you simply need to adjust the variable with what you need.

这篇关于如何使用Javascript模拟输入框中的键入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆