编程语言
1 前言
一个问题,一篇文章,一出故事。
笔者最近需要一段JavaScript模拟人类向文本框输入字符,于是整理此文。
2 最佳实践
<!DOCTYPE html> <html> <head> <title>模拟人类向文本框输入字符串</title> </head> <body> <input type="text" id="my-textbox" value=""> <input my-id="my-text" type="text" value=""> <script> //var input = document.querySelectorAll("input")[0]; //var input = document.querySelector('#my-textbox'); var input = document.querySelector('input[my-id="my-text"]'); input.select(); // you can also use input.focus() input.value=""; var inputText = "will@cmdschool.org"; var textLength=inputText.length; var textCurrent = 0; var time = 50; var write_text = function() { input.value+=inputText[textCurrent]; if(textCurrent < textLength-1) { textCurrent++; setTimeout(function(){write_text()},time); } else { input.setAttribute('value',input.value); } } setTimeout(function(){write_text()},time); </script> </body> </html>
以上使用文本编辑器,保存到电脑本地使用浏览器运行即可测试,另外,以下范例也可以参阅,
<!DOCTYPE html> <head> <title>模拟人类向文本框输入字符串</title> </head> <body> <input type="text" id="my-textbox" value=""> <input my-id="my-text" type="text" value=""> </body> <script type="text/javascript"> function fireKeyEvent(element, evtType, keyChar) { element.focus(); var KeyboardEventInit = {key:keyChar, code:"", location:0, repeat:false, isComposing:false}; var evtObj = new KeyboardEvent(evtType, KeyboardEventInit); element.dispatchEvent(evtObj); } //var objInput = document.getElementById("my-textbox"); var objInput = document.querySelector('input[my-id="my-text"]'); objInput.addEventListener('keydown', function (e) { objInput.value += e.key; }, false); const inputString = 'will@cmdschool.org'; for (let i = 0; i < inputString.length; i++) { const char = inputString.charAt(i); console.log('char', char) fireKeyEvent(objInput,"keydown",char); } </script> </html>
参阅文档
================
https://stackoverflow.com/questions/47617616/how-to-simulate-typing-in-an-input-box-with-javascri
没有评论