简体   繁体   English

模拟用户在文本框 javascript 中书写

[英]Simulate user writing in a textbox javascript

I have this form and I write into it using:我有这个表格,我用:

document.getElementById("val").value ="value";

This inserts the value automatically into the textbox.这会自动将值插入到文本框中。

Is it possible to insert it simulating user writing?是否可以插入模拟用户写作? So inserting a letter one by one and not all together?所以一个一个地插入一个字母而不是全部插入?

Check if this works for you. 检查是否适合您。 It will insert the character one by one with delay of around 300ms between each character. 它将一个接一个地插入字符,每个字符之间的延迟约为300毫秒。

 var word = "value"; var n = 0; var x = document.getElementById("val"); (function loop() { x.value += word[n]; if (++n < word.length) { setTimeout(loop, 300); } })(); 
 <input type="text" id="val"> 

Take a look on it: 看一看:

function typeWriter(txt, element, speed, i=0) {
    if (i < txt.length) {
        document.getElementById(element).innerHTML += txt.charAt(i);
        i++;
        setTimeout(function() {typeWriter(txt, element, speed, i);}, speed);
    }
}

txt - Text to write, txt要写的文字,

element - id of element (eg val , without # ), element ID(例如val ,不带# ),

speed - speed of writing in ms. speed -以毫秒为单位的写入速度。

 const input = document.getElementById("val"); input.select(); const textMessage = "The message that you want to display"; let currentIndex = 0; const delay = 400; const writeText = function() { input.value += textMessage[currentIndex]; if (currentIndex < textMessage.length - 1) { currentIndex++; setTimeout(function() { writeText() }, delay * Math.random()); } else { return } } writeText() 
 <input id="val" type="text" /> 

Yes you can simulate a user typing in an input field, by using the built-in setInterval method which repetitively calls a function after a delay. 是的,您可以使用内置的setInterval方法模拟用户在input字段中键入内容,该方法在延迟后重复调用函数。

Here's a demo: 这是一个演示:

In the demo, I implemented a function that receives two arguments: the first argument is the input element's ID and the second one is the text that you want to be written in that field. 在演示中,我实现了一个函数,该函数接收两个参数:第一个参数是input元素的ID ,第二个参数是要在该字段中编写的文本。

The setInterval method's second argument is the delay(the time which the callback function is called after) which you can change to suit your needs. setInterval方法的第二个参数是delay(可以在以后调用回调函数的时间),您可以根据需要进行更改。

 function simulateWriting(inputId, val) { var inp = document.getElementById(inputId), i = 0, l = val.length, intervalId = setInterval(function() { (i < l) ? inp.value += val[i++]:clearInterval(intervalId); }, 500); } // calling the function with input id=input-val and value='some value'. simulateWriting('input-val', 'some value'); 
 <input type="text" id="input-val" /> 

An example that allows an onset delay, interresponse-time between keystrokes, preservation of cursor position, as well as native change event triggers:一个允许开始延迟、击键之间的交互响应时间、保留光标位置以及本机更改事件触发器的示例:

 let target = document.getElementById('testarea') target.selectionStart = 30; target.focus(); /** * simulateTextareaInput * @param id {string} The id of the textarea to target. * @param text {string} The text to input, character-by-character. * @param lat {number} The latency / time to wait before beginning input. * @param irt {number} The interresponse-time between each input / simulated keystroke. */ const sim = function (id, text, lat, irt) { const length = text.length-1; var current = 0; /** * insertText * @param str {string} The character to input into the text area */ const insertChar = function(char) { // get element var target = document.getElementById(id); if (target !== null) { // if it is found in the dom ... let [start, end] = [target.selectionStart, target.selectionEnd]; // insert char target.setRangeText(char, start, end, 'select'); // move cursor forward 1 target.selectionStart = start+1; // trigger any onChange listeners var event = new window.Event('change', { bubbles: true }); target.dispatchEvent(event); } else { console.log(`No <textarea> with id "${id}" found.`) }; }; const write = function() { // insert current character insertChar(text[current]); if(current < length) { // so long as there are more chars to input current++; // increment setTimeout(function(){write()},irt); // recurisvely write next char }; }; setTimeout(function(){ // kickoff input setTimeout(function(){write()},irt) },lat); // wait this long before starting }; sim('testarea','this text was simulated after 2s -- cool!',2000,50);
 textarea { width: 500px; height: 100px; }
 <!-- begin demo --> <textarea id='testarea'> hello world simulated output: new text will appear on the above line </textarea>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM