【发布时间】:2013-08-13 15:51:28
【问题描述】:
我在 javascript 函数中有一些 jQuery,可以更改页面上的文本并以特定时间间隔淡入和淡出。我希望函数一个接一个地运行,在每个函数完成其效果之后。
dialogueExchange1();
dialogueExchange2();
dialogueExchange3();
function dialogueExchange1() {
$('.text-area1').text("hey");
$('.text-area1').delay(1000).showDialogue(800, 3000).prepareDialogue(800, "hey, are you awake?");
}
function dialogueExchange2() {
$('.text-area1').delay(900).showDialogue(800, 4000).prepareDialogue(800, "wake up").delay(900);
$('.text-area2').text("...");
$('.text-area2').delay(1200).showDialogue(800, 1500).fadeOut(800);
}
function dialogueExchange3() {
$('.text-area1').delay(900).showDialogue(800, 4000).prepareDialogue(800, "let's go").delay(900);
$('.text-area2').text("not yet");
$('.text-area2').delay(1200).showDialogue(800, 1500).fadeOut(800);
}
showDialogue 和 prepareDialogue 是我创建的延迟和淡入淡出文本的方法。那工作正常。基本上,我只是想让文本在特定时间后更改文本区域选择器中的文本。当前正在发生的是所有功能都在同时运行,因此同时触发了文本更改效果。我希望dialogueExchange1 做它的效果,然后当它完成时,让dialogueExchange2 做它的效果,然后当它完成时等等。
我已经尝试通过以下解决方案来处理队列、超时和回调,但我并没有完全按照我的意愿去做:
How do I chain or queue custom functions using JQuery?
我过去有这个工作,只是通过将所有文本更改方法链接到一行代码中来做我想做的事情,但它看起来很糟糕。将其分解为功能并按顺序运行将使其更有条理,有助于跟踪文本更改和延迟时间。谢谢!
编辑:showDialogue 和 prepareDialogue 按要求运行
$.fn.showDialogue = function(fadeInTime, showTextTime) {
this.fadeIn(fadeInTime).delay(showTextTime);
return this;
};
$.fn.prepareDialogue = function(fadeOutTime, dialogue) {
this.fadeOut(fadeOutTime, function() {
$(this).html(dialogue);
});
return this;
};
解决方案 EDIT2:感谢大家的回复,感谢whoughton 首先建议使用promise()。这是我目前的解决方案,但我确信我会在看到 Shaunak 的回答后对其进行重构并更改它。
dialogueExchange1();
function dialogueExchange1() {
$('.text-area1').text("hey");
$('.text-area1').delay(1000).showDialogue(800, 3000).prepareDialogue(800, "hey, are you awake?");
$('.text-area1, .text-area2, .text-area3').promise().done(function() {
dialogueExchange2();
});
}
function dialogueExchange2() {
$('.text-area1').delay(900).showDialogue(800, 4000).prepareDialogue(800, "wake up");
$('.text-area3').text("...");
$('.text-area3').delay(1800).showDialogue(800, 1500).fadeOut(800);
$('.text-area1, .text-area2, .text-area3').promise().done(function() {
dialogueExchange3();
});
}
function dialogueExchange3() {
$('.text-area1').delay(900).showDialogue(800, 4000).prepareDialogue(800, "come on let's go");
$('.text-area2').text("hold on");
$('.text-area2').delay(1200).showDialogue(800, 1500).fadeOut(800);
}
通过这种方式,我可以灵活地优化延迟时间以反映和模仿对话。下一个函数仅在函数中的效果完成时运行,promise() 使之成为可能。如果您想看到它的实际效果,这里是jsFiddle link。
【问题讨论】:
-
你能准备一个实际代码的小提琴吗?因为您的问题的解决方案取决于 showDialogue 和 prepareDialogue 函数中发生的情况。
-
添加了 showDialogue 和 prepareDialogue 函数
-
好的,我在下面添加了一个适合您的答案。我创建了一个非常简单的通用示例,所以你明白了。然后如何将其应用于您的案例。您可以使用它按您想要的顺序链接任意数量的动画函数。
标签: javascript jquery