执行一个接一个的功能

时间:2013-04-21 23:54:28

标签: jquery

在完成一个功能后,我很难让另一个功能工作。我的代码的前半部分可以工作,但之后的功能却没有。我做错了什么?

HTML

<div id="feature">
    <div id="open"></div>
</div>

CSS

#feature {
    position:relative;
    width:100%;
    height:450px;
}
#open {
    position:relative;
    width:100%;
    height:200px;
    background:red;
}

jQuery

$('#open').click(function () {
    $(this).animate({
        height: 50
    }, {
        duration: 'slow'
    }).css('overflow', 'visible'),
    function () {
        $('#open').animate({
            height: 200
        }, {
            duration: 'slow'
        })
    };
    // Animation complete.
});

JS小提琴。

http://jsfiddle.net/C8fA7/

2 个答案:

答案 0 :(得分:1)

该函数需要是animate的参数,但是在完成对css的调用很久之后,您已将其放在animate之后。试试这个:

$(this).animate({
    height: 50
}, {
    duration: 'slow'
}, function () {
    $('#open').animate({
        height: 200
    }, {
        duration: 'slow'
    })
}).css('overflow', 'visible');

如果我们明确指出链接,那就更清楚了:

var temp = $(this);
temp = temp.animate({ height: 50 }, { duration: 'slow' });
temp = temp.css('overflow', 'visible');

那时,你刚刚离开了这个迷路函数:

function () {
    $('#open').animate({ height: 200 }, { duration: 'slow' });
}

那里没有语法错误,但它什么也没做,因为它从未被调用过。

此外,您的评论// Animation complete表示您可能没有意识到动画是异步的。完成animate语句后,动画已启动,但尚未完成。动画完成后,将调用您的回调函数; animate来电之后的陈述不会等待。

答案 1 :(得分:0)

这是最简单的方法:

// Do stuff (Pt. 1)
setTimeout(function() {
    // Do more stuff (Pt. 2)
    setTimeout(function() {
        //Do even more stuff (Pt. 3)...
    }, 0);
}, 0);

不确定 ES/JS 是否打算以这种方式使用 setTimeout,但即使指定了 0ms 的持续时间,该函数仍然遵循 when/then 或 when/done 'sequence' 等待第一个函数(或操作)在继续之前完成。后续函数被称为“回调”,尽管我认为这是一个糟糕的词选择 - 它们不会回调任何东西并继续前进!

相关问题