【问题标题】:Text append and cycle through effect文本附加和循环效果
【发布时间】:2017-01-08 23:12:06
【问题描述】:

我正在尝试使用数组上的字符串通过文本淡入/淡出效果实现循环。例如,我从 span 标签内的初始文本(“Los Angeles”)开始。我希望此文本从字符串“洛杉矶”更改为“萨克拉门托”,并带有淡入淡出的动画和中间的延迟,我试图通过计时功能来实现。我正在定义一个数组,在其中存储要循环遍历的字符串。我遇到的问题是我只能将字符串从数组的第一个元素更改为最后一个元素。介于两者之间的元素,例如旧金山和伯克利,会被 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>     

【问题讨论】:

    标签: javascript jquery html arrays dom


    【解决方案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);
    })
    

    【讨论】:

    • 对不起!
    • 如何重新启动循环?我们的想法是从最后一个字符串之后的第一个字符串重新开始。
    • 没关系。谢谢您的帮助。如果有人感兴趣,请在以下线程上找到答案:stackoverflow.com/questions/18536436/…
    【解决方案2】:

    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>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-02
      • 2017-12-27
      • 2017-05-21
      相关资源
      最近更新 更多