将字符数组写入元素不会打印第一个字母

时间:2017-02-04 16:11:18

标签: javascript jquery arrays

我正在尝试一次将一个字符写入一个单词数组中的元素。我遍历一个单词数组,将每个单词分成一个字符数组。从那里,我遍历字符数组到jQuery.append每个字母到目标元素。对于除循环中的第一个单词之外的任何单词,第一个字母不会写入元素。 Console.log(字母)显示脚本正在拾取信件。我想这可能是因为我在每个单词之后将目标元素淡出并重新进入。

var words = ["demo", "sample", "taco", "potato"];

$(document).ready(function() {
  typeStuff();
});

function typeStuff() {
  //if the type target element does not exist, create it. Runs once.
  if (!$("#typeTarget").length) {
    $("#typeHere").append("<span id='typeTarget'></span>");
  }

  //Create a string of tbe next word, then arrayify it.
  var w = words.shift();
  var wordAsArray = w.split("");

  //create a 450 ms interval to type each word out.
  var interval = window.setInterval(function() {
    //First, check if no letters are left.
    if (wordAsArray.length == 0) {
      //If no letters are left, see if there's another word to pickup
      if (words.length == 0) {
        //Clear the interval, your work is done. Good job, scripto.
        window.clearInterval(interval);
      } else {
        //Clear the interval and run the delete function.
        window.clearInterval(interval);
        deleteStuff();
      }
    } else {
      //If any letters are left, get the next letter and append it to #typeTarget
      var letter = wordAsArray.shift();
      $("#typeTarget").append(letter);
    }
  }, 450);
}

function deleteStuff() {

  //Fade #typeTarget out, delete its contents, then show it again.
  $("#typeTarget").fadeOut(500, function() {
    $("#typeTarget").html("");
    $("#typeTarget").css({
      display: "inline"
    });
  });

  //Call the typeStuff function again to write the next word.
  typeStuff();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="titleText">This is a <span id="typeHere"></span></span>

1 个答案:

答案 0 :(得分:1)

Pointy指出:

  

对,你的淡出需要500毫秒,但间隔计时器的第一次迭代在此之前50毫秒发生。

将渐弱校正为300毫秒,纠正了这一点。