在javascript中模拟打字的外观,而不是实际的按键 [英] Simulate the look of typing, not the actual keypresses, in javascript
问题描述
我正在尝试编写一个简单的函数,使其看起来好像有人正在键入 textarea
I'm trying to write a simple function that will make it appear as though someone is typing in a textarea
- 这是我的功能(原谅我,如果它的残暴,但我通常不使用javascript)---
console.log()
部分工作正常,但由于某种原因,我无法得到这个脚本来更新dom的方式,我会期望...
-- This is my function (forgive me if its atrocious, but I don't normally use javascript) ---
The console.log()
part works fine, but for some reason I cannot get this script to update the dom the way I would expect...
function type(string) {
value = "";
el = document.getElementById("typeArea");
for (var i = 0; i < string.length; i++) {
value += string[i];
//$("#fbw > textarea").val(value);
el.textContent = value;
console.log(value);
sleep(160);
}
sleep(2000);
}
感谢您能给我的任何见解。
I appreciate any insight you can give me.
推荐答案
jsFiddle Demo
你所缺少的是一个构造,而不是睡眠
。实现这一点的js方法是使用超时和递归调用来遍历字符串
All you were missing was a construct instead of Sleep
. The js approach for accomplishing this is to use a timeout and a recursive call in order to iterate through your string
function type(string,element){
(function writer(i){
if(string.length <= i++){
element.value = string;
return;
}
element.value = string.substring(0,i);
if( element.value[element.value.length-1] != " " )element.focus();
var rand = Math.floor(Math.random() * (100)) + 140;
setTimeout(function(){writer(i);},rand);
})(0)
}
这篇关于在javascript中模拟打字的外观,而不是实际的按键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!