0

我试图取一个句子并通过闪烁单词,最后一个单词淡出,持续更长的时间。

由于某种原因,它只处理数组中的最后一个字符串。

谢谢你的时间 : )

jsfiddle

<script>
    $(function() {

    //take sentence
      var lines = [
        'Apples are red',
        'Sky is blue',
        'Grass is green'
      ];
    //set index
    var i = 0;

    showLinesHelper();

    function showLinesHelper()  {
    //take line and split into words
      words = lines[i].split(' ');
      $.each(words, function(k, v)  {
    //take each word and flash
        if(k != words.length)  {
    //if not last word
          setTimeout(function()  {
    //display word into class
            $('.words').html(v);
    //take array index x milliseconds
          }, k * 500);
        }else  {
    //last word
          setTimeout(function()  {
    //display word into class
            $('.words').html(v);
    //take array index x milliseconds
    //show last word for a longer amount of time
          }, k * 1000);
        }
      });
      i++;
      if(i < lines.length)  {

    //if array is less than index, call again
        setTimeout(showLinesHelper(), 0);

      }
    }

    });
</script>

    <div class="words">
    </div>
4

1 回答 1

1

我对您的代码进行了一些更改,我创建了一个新的变量time来保持超时的新计数,并在IF条件中添加了一个-1 ,因为数组长度从 0 开始并且ELSE从未命中它。

$(function() {

//take sentence
  var lines = [
    'Apples are red',
    'Sky is blue',
    'Grass is green'
  ];
var i = 0;
var time = 1;
showLinesHelper();

function showLinesHelper()  {
//take line and split into words
  words = lines[i].split(' ');
  $.each(words, function(k, v)  {
//take each word and flash

    if(k != words.length - 1)  {
//if not last word

      setTimeout(function()  {
//display word into class
        $('.words').html(v);
//take array index x milliseconds
      }, time * 500);
      time = time + 2;
    }else  {
//last word

      setTimeout(function()  {
     
//display word into class
        $('.words').html(v);
//take array index x milliseconds
//show last word for a longer amount of time
      }, time * 500);
      time = time + 5;
    }
  });
  i++;
  if(i < lines.length)  {

//if array is less than index, call again
    setTimeout(showLinesHelper(), 0);

  }
}

});

于 2018-11-15T21:24:27.760 回答