我尝试创建基于淡出的文本更改动画 - 更改文本 - 淡入概念,将作为无限循环运行,循环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问题,但似乎没有一个问题能解决我的问题。
我尝试了setInterval,window.function,for循环和其他一些解决方案,他们或者抛出过多的递归错误或者崩溃我的浏览器或根本不工作。要么它甚至不应该以那种方式工作,要么我做得不对。
这是我试图改变的HTML:
<div class="container"><span id="changeText">blah</span></div>
答案 0 :(得分:1)
您正在使用&#39; this
&#39;在代码的开头引用,但是它错过了它所指向的元素的上下文。此外,由于您的元素具有ID&#39; changeText
&#39;,因此您只需将其直接定位在您的选择器中即可。
$(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);
答案 1 :(得分:0)
我一定是傻瓜,解决方案对我来说太简单了。我甚至试过它,但我必须写错了,这使它无法正常工作。这段时间我一直试图重新调用&#39; $(文档).ready&#39;中的函数。范围之外的范围几乎是不可能的,但我实际上并不需要这样做。
我刚刚在其中创建了一个普通的JavaScript函数,它在函数外部被调用一次,并且每次重新调用都是从最后一次.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();