简体   繁体   English

Javascript用字符串替换onKeyUp事件

[英]Javascript Replace onKeyUp event with a string

Im not very good at JavaScript and need a hand with what I think is an easy script. 我不太擅长JavaScript,我需要一个简单的脚本。 Basically I have an input box that when the user types in a key it will disappear and change to whatever string I have. 基本上,我有一个输入框,当用户键入一个键时,它将消失并更改为我拥有的任何字符串。 I could only get the one letter to change, so that I have something to show what i mean. 我只能得到一封要更改的字母,这样我才能显示出我的意思。 So whenever a user types a message it gets replaced with an "h", what I want though is to have "hello" typed out letter by letter and not just "h" all the time and not "hello" all at once. 因此,每当用户键入一条消息时,它都会被替换为“ h”,但我想要的是让“ hello”逐个字母地输入,而不仅仅是一直输入“ h”,而不是一次都输入“ hello”。

Here is the code. 这是代码。

<form action=# name=f1 id=f1 onsubmit="return false">

<input type=text name=t1 id=t1 value="" size=25 style="width:300px;" 
    onkeypress="if(this.value.match(/\D/))"
    onkeyup   ="this.value=this.value.replace(/\D/g,'h')">

</form>

JUST EDITED AS IT IS GIVING JS ERROR HOPE YOU WONT MIND:Are you trying something like this: 刚刚进行编辑,因为它提供了JS错误希望,但您没有想到:您是否正在尝试执行以下操作:

 function replaceString(el){ var sampleText = "hello".split(""); var value = ""; console.log(el) el.value.split("").forEach(function(str, index){ value += sampleText[index%sampleText.length]; }); el.value = value; } 
 <form action=# name=f1 id=f1 onsubmit="return false"> <input type=text name=t1 id=t1 value="" size=25 style="width:300px;" onkeypress="if(this.value.match(/\\D/));" onkeyup ="replaceString(this);"/> </form> 

If you want to simulate typing text into the textbox then you will need to use a timeout. 如果要模拟在文本框中输入文本,则需要使用超时。 The following function should suffice: 以下功能就足够了:

function simulateTyping(str, el)
{
    (function typeWriter(len)
    {
      var rand = Math.floor(Math.random() * (100)) + 150;
      if (str.length <= len++)
      {
        el.value = str;
        return;
      }
      el.value = str.substring(0,len);
      if (el.value[el.value.length-1] != ' ')
        el.focus();
      setTimeout(
        function()
        {
          typeWriter(len);
        },
        rand);
    })(0);
}

You'll need to pass it two parameters : the string to type eg "hello" and the element into which to type the string. 您需要向其传递两个参数:要键入的字符串(例如“ hello”)和要在其中键入字符串的元素。 Here's a simple wrapper function: 这是一个简单的包装函数:

function typeHello() {
  var el = document.getElementById('t1');
  var str = 'hello';
  simulateTyping(str, el);
}

When you call the typeHello function it will find the element with the "t1" id and type the "hello" text. 当您调用typeHello函数时,它将找到具有“ t1” ID的元素,然后键入“ hello”文本。

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

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