jQuery 闪词

jQuery Flash Words

我正在尝试对一个句子进行闪烁,最后一个词淡出,持续更长的时间。

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

感谢您的宝贵时间:)

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>

我对您的代码做了一些更改,我创建了一个新变量 time 来保持新的超时计数,并添加了一个 -1IF 条件,因为数组长度从 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);

  }
}

});