jQuery 动画改变文本无限循环

jQuery animate changing text infinite loop

我正在尝试创建一个基于淡出 - 更改文本 - 淡入概念的文本更改动画,该动画将 运行 作为一个无限循环,围绕 3 个不同的文本,中间有 2 秒的停顿。

我的 Javascript 文件中有这个 jQuery 代码:

$(document).ready(function changeText(){
    $(this).find("#changeText").delay(2000).animate({opacity:0},function(){
        $(this).text("foo").animate({opacity:1},function(){
            $(this).delay(2000).animate({opacity:0},function(){
                $(this).text("bar").animate({opacity:1}, function(){

                });
            });
        });
    });
});

它做了它应该做的,但是,当然,只有一次。无论我做什么,我似乎都无法让它作为一个循环工作。我浏览了很多类似的 Stack Overflow 问题,但是 none 似乎已经解决了我的问题。

我尝试了 setInterval、window.function、for 循环和其他一些解决方案,但它们要么抛出关于太多递归的错误,要么使我的浏览器崩溃,要么根本不起作用。要么它甚至不应该那样工作,要么我做的事情不对。

这是我要更改的 HTML:

<div class="container"><span id="changeText">blah</span></div>

您在代码的开头使用了“this”引用,但它缺少它指向的元素的上下文。此外,由于您拥有 ID 为“changeText”的元素,因此您可以直接在选择器中将其作为目标。

  $(document).ready(function(){
    $("#changeText").delay(2000).animate(
    {opacity:0 },function(){
       $(this).text("foo").animate({opacity:1},function(){
        $(this).delay(2000).animate({opacity:0},function(){
            $(this).text("bar").animate({opacity:1}, function(){
            });
        });
    });
  });
});

工作示例:https://jsfiddle.net/q1o2f5jx/

编辑:

要改进代码,请在数组中添加文本并增加 setInterval 的索引。

var textArray = ["foo","bar","blah1","blah2"];
var index = 0;
setInterval(function(){        
$("#changeText").animate({
opacity:0
},function()
{
   if(textArray.length > index) {
   $(this).text(textArray[index]).animate({opacity:1})
   index++; 
   }
   else
   index = 0;
});
},2000);

工作示例:https://jsfiddle.net/q1o2f5jx/2/

我一定是傻了,解决方案太简单了,我看不出来。我什至试过了,但我一定是写错了什么导致它不起作用。一直以来,我都在尝试从范围外重新调用 '$(document).ready' 范围内的函数,这几乎是不可能的,但实际上我不需要这样做。

我刚刚创建了一个普通的 JavaScript 函数,里面有 jQuery,它在函数外部被调用一次,并且每次重新调用都是从最后一个 .animate() 回调进行的。

function changeText(){
    $("#changeText").delay(2000).animate({opacity:0},function(){
        $(this).text("foo").animate({opacity:1},function(){
            $(this).delay(2000).animate({opacity:0},function(){
                $(this).text("bar").animate({opacity:1},function(){
                    $(this).delay(2000).animate({opacity:0},function(){
                        $(this).text("blah").animate({opacity:1},function(){
                            changeText();                           
                        });
                    });
                });
            });
        });
    });
};

changeText();