文本追加和循环效果

时间:2017-01-08 23:12:06

标签: javascript jquery html arrays dom

我试图通过数组上的字符串来实现文本淡入/淡出效果的循环。例如,我从span标签内的初始文本(" Los Angeles")开始。我想要从字符串"洛杉矶"到了萨克拉门托"使用fadein动画和介于两者之间的延迟,这是我试图通过计时功能实现的。我定义了一个数组,我存储了我想要循环的字符串。我遇到的问题是我只能将字符串从数组的第一个元素更改为最后一个元素。其中的元素,如旧金山和伯克利,被for循环忽略了。我究竟做错了什么?谢谢。任何帮助表示赞赏。这是我到目前为止所得到的:

  <div id="fly" class="container-fluid section text-center">
  <h1 id="intro-txt">Go from <br> <span id="dest1" style="color: #b9b7b7;">Los Angeles</span> to <span id="dest2" style="color: #b9b7b7;">Las Vegas</span> <br> with no hassle.</h1>
  <script>

  var from = ["San Francisco", "Berkeley", "Place3"];
  var to = ["Sacramento", "New Mexico", "Place3"];
  var total = from.length;
  var index = 0;

  $(document).ready(function(){
    for(index; index < total; index++){
      var fromLoc = from[index];
      var toLoc = to[index];


      var textScroll = function(){
        var start = $("#dest1")
        $("#dest1").fadeOut(function() {
          $(this).text(fromLoc).fadeIn();

        });
        $("#dest2").fadeOut(function() {
          $(this).text(toLoc).fadeIn();
        });            
      }
      setTimeout(textScroll, 2000);
    }
  });
  </script>     

2 个答案:

答案 0 :(得分:1)

您正在创建多个setTimeout,但它们几乎会在同一时间运行。

使用循环索引作为持续时间乘数来创建时间偏移。你还需要一个闭包,因为index的值在函数运行之前将达到最大值。见JavaScript closure inside loops – simple practical example

var textScroll = function(fromLoc, toLoc) {
  var start = $("#dest1")
  $("#dest1").fadeOut(function() {
    $(this).text(fromLoc).fadeIn();

  });
}
$.each(from, function(index, fromLoc) {
  var toLoc = to[index];
  setTimeout(function() {
    textScroll(fromLoc, toLoc);
  }, index * 4000);
})

答案 1 :(得分:0)

var from = ["San Francisco", "Berkeley", "Place3"];
var to = ["Sacramento", "New Mexico", "Place3"];
var total = from.length;
var i = 0;
setInterval(function (){
    $("#dest1").fadeOut(1000,function(){$(this).text(from[i])}).fadeIn(1000);
    $("#dest2").fadeOut(1000,function(){$(this).text(to[i])}).fadeIn(1000);
    if (i >= total-1) i = 0;
    else i++;
},2200);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="fly" class="container-fluid section text-center">
  <h1 id="intro-txt">Go from <br> <span id="dest1" style="color: #b9b7b7;">Los Angeles</span> to <span id="dest2" style="color: #b9b7b7;">Las Vegas</span> <br> with no hassle.</h1>
</div>