在javascript中模拟键入的外观,而不是实际的按键

Simulate the look of typing, not the actual keypresses, in javascript

本文关键字:外观 javascript 模拟      更新时间:2023-09-26

我想写一个简单的函数,使它看起来好像有人在输入textarea

——这是我的函数(原谅我,如果它很糟糕,但我通常不使用javascript)——console.log()部分工作得很好,但由于某种原因,我无法让这个脚本以我期望的方式更新dom…

        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);
        }
我很感激你能给我的任何见解。

jsFiddle Demo

你所缺少的只是一个构式而不是Sleep。js实现这一点的方法是使用超时和递归调用来遍历字符串

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

您可以使用setTimeout函数做类似的事情。 Codepen

$(function(){
  simulateTyping('looks  like someone is typing...', '#txt')
  function simulateTyping(str, textAreaId) {
    var textArea = $(textAreaId);
    var currentCharIndex = 0;
    function typeChar(){
      if (currentCharIndex >= str.length)
        return;
      var char = str[currentCharIndex];
      textArea.val(textArea.val() + char);
      currentCharIndex ++;
      setTimeout(typeChar, 500);
    } 
    typeChar();
  }
})