首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在jQuery调用序列中等待效果队列的完成

问如何在jQuery调用序列中等待效果队列的完成
EN

Stack Overflow用户
提问于 2014-04-17 19:14:42
回答 2查看 1.7K关注 0票数 0

我在寻找一些功能:

  • 将能够等待队列中的所有效果完成。
  • 可以用于经典的jQuery调用序列中。

示例:

我想做一些动画,然后在它们完成后进行一些操作:

代码语言:javascript
复制
$('.obs_list')
.delay(500)
.animate({
        'background-color' : '#ffcc33'
}, 200)
.delay(1000)
.animate({
        'background-color' : 'transparent'
}, 2000)
.THE_FUNCTION_I_AM_LOOKING_FOR() 
.css({ 'color' : 'red' }) // this should come *after* the effects above are finished
...

我想避免使用动画函数的回调,因为您必须在其中再次调用jquery,它不是很优雅,并且打破了链:

代码语言:javascript
复制
...
.animate({
        'background-color' : 'transparent'
}, 2000, function () {
        $(this)
        .css({ 'color' : 'red' })
        ...
});

我讨厌这个解决方案。

我尝试使用.promise(),但这也破坏了链,因为它显然没有返回正确的jQuery对象。请避免编写新插件:-)

EN

回答 2

Stack Overflow用户

发布于 2014-04-17 19:34:51

你有几个选择:

queue

代码语言:javascript
复制
.animate(...)
.queue(function (n) {
    $(this).css('color', 'red');
    n();
});

当每个元素在队列中达到此函数时,将在集合中的每个元素调用一次queue回调。这意味着队列回调将被多次调用,如果项目具有不同的动画,则可能在不同的时间调用。

promise (与done一起):

代码语言:javascript
复制
.animate(...)
.promise()
.done(function () {
    $(this).css('color', 'red');
});

在集合中的所有元素完全清空队列后,将调用一次done回调。这是有用的,如果你有一堆动画发生,你想触发一些事情发生时,他们都已经完成。

一个定制的jQuery插件:

代码语言:javascript
复制
//I wrote this on the fly and it looks like it should work
//I haven't tested it, so let me know if there are any bugs
$.fn.queuedCSS = function () {
    var args = Array.prototype.slice.call(arguments);
    return this.queue(function (n) {
        $.fn.css.apply($(this), args);
        n();
    });
};

.animate(...)
.queuedCSS('color', 'red');

animate调用的完整回调:

代码语言:javascript
复制
.animate(..., function () {
    $(this).css('color', 'red');
});

当该特定元素上的特定动画完成后,将运行完整的回调。

立即执行(几乎)的动画:

代码语言:javascript
复制
.animate(...)
.animate({'color': 'red'}, 1);

因为动画是fx队列的一部分,而且持续时间非常短,所以动画将完成并设置样式。

现在,我知道您不喜欢这些解决方案,但这太糟糕了,因为它们是----解决方案。css函数不与fx队列交互,因此如果希望它成为定时队列的一部分,必须在回调中以某种方式使用它。

票数 5
EN

Stack Overflow用户

发布于 2014-04-17 19:45:51

虽然它不是很优雅,但它是实现您想要的东西的一种方法,但是尝试下面的代码片段:

代码语言:javascript
复制
var elements = $('.obs_list');
elements
.delay(500)
.animate({
        'background-color' : '#ffcc33'
    //see the use of proxy here to change the scope of callback function
}, 200, $.proxy(function(){
        this
        .css({ 'color' : 'red' });
}, elements)

您可以找到更多关于代理这里的信息。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/23141572

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档