如何使所需的文字逐字显示

时间:2016-11-20 19:50:13

标签: javascript jquery

我有一个函数可以将文本附加到div中并带有一些颜色效果。 我想让文字一字接一句地出现。 (但我只需要在第二个函数的参数“str”的文本中使用此效果,“who”必须显示正常。 我找到了一个我需要的效果的示例代码,但我不知道如何使两个函数一起工作。

JS:

// my function
    var showText = function(who, str) {
      if(str !== "") {
        $("#storyBoard").append("<p><span style='color:#323232;'>" + who.name + ": " + "</span>" + str + "</p>");
      };
    };

showText(somObj, "The text i want to append on the page when calling the function");

    // the function i want to add into my first function
    $(function() {
      var a = new String;
      a = $('.text_cont_inner').text();
      $('.text_cont_inner').text('');
      var c = a.length;
      j = 0;
      setInterval(function() {
        if(j < c) {
          $('.text_cont_inner').text($('.text_cont_inner').text() + a[j]);
          j = j + 1;
        } else {
          $('.text_cont_inner').removeClass('after')
        }
      }, 100);
    });

HTML:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" type="text/css" href="css/style.css">
    <title>MacroG0D - My first game</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src ='Js/main.js' type="text/javascript"> </script>
</head>
<body>
<div id = "storyBoard">
<h1> Star Wars - Healing <br>The Breach:<hr></h1>

<p class="intro">A long time ago, in a galaxy far, far away</p>
<p> Welcome to the virtual pseudo-reality. Are you ready to start this journey? </p>
</div>
<input type="text" id ="myInput" placeholder="Type the command here" name="myInput" autofocus autocomplete='off'/>
<button id="btn" type="submit"> Enter </button>

</body>
</html>

1 个答案:

答案 0 :(得分:1)

试试这个:)

var showText = function(who, str) {
  if(!str){
    return;
  }

  var textNode = $("#storyBoard") // take container
    .append("<p><span style='color:#323232;'>" + who.name + ": </span><span></span></p>") // add contents
    .find("p span:last-сhild")[0]; // select last <span> to put str value into

  var words = str.split(" "); // break a string on words
  var intervalId = setInterval(function() { // set new interval and remember it's ID
    if (!words.length) { // no words left in array
      return clearInterval(intervalId); // stop running interval and exit
    }

    textNode.innerText += " " + words.shift(); // add space and next word
  }, 100); // milliseconds between word insertions
};