开发者

How can an animation be queued for different elements?

I have a question about animation queues in jQuery. Let's talk over an example.

Let say I have a div and a bunch of p elements in it and some of those p elements has class like "read":

<div class="wrapper">
    <div class="inner">
        <p>Paragraph 1</p>
        <p class="read">Paragraph 2</p>
        <p>Paragraph 3</p>
        <p class="read">Paragraph 4</p>
        <p>Paragraph 5</p>
        <p class="read">Paragraph 6</p>
        <p>Paragraph 7</p>
        <p class="">Paragraph 8</p>
    </div>
</div>

I'd like to fade the read ones out and animate the height of the wrapping div element accordingly. This jQuery code block won't work.

var initHeight = $('.wrapper').height();
$('.wrapper').height(initHeight);
$('p').not('.read').fadeOut(30开发者_StackOverflow中文版0, function() {
    $('.wrapper').animate({
        height: $('.inner').height()
    }, 300);
});

The reason is, after each .fadeOut our height animation will be called and as a result, div.wrapper's height will be adjusted step by step. Here you can find the example:

http://jsfiddle.net/7gW5w/2/

So I changed the script like the one in below:

var initHeight = $('.wrapper').height();
$('.wrapper').height(initHeight);
$('p').not('.read').fadeOut(300, function() {
    if ($(this).is(':last-child')) {
        $('.wrapper').animate({
            height: $('.inner').height()
        }, 300);
    }
});

Example: http://jsfiddle.net/7gW5w/3/

In this case if we remove "read" class from the last element, it will run smoothly as I desired. However, the last p element could have "read" class. So this is not a solution either.

This is just an example to visualize my question. There can be lots of examples around. My question is, is there a method to queue my height animation, after each p element completes it's own fadeOut animation. Hypothetical syntax:

var initHeight = $('.wrapper').height();
$('.wrapper').height(initHeight);
$('p').not('.read').fadeOut(300);
$('p').not('.read').queueAfter(function() {
    $('.wrapper').animate({
        height: $('.inner').height()
    }, 300);
});

So that after all p element completes its fadeOut animation, my height animation will be triggered.

I hope I could make my self clear.

Thanks in advance.

Ugur


good question.

i think you can solve your problem using the :last selector. my idea was to only provide a callback for the last element. like this:

$('p').not('.read').filter(':not(:last)').fadeOut(300);
$('p').not('.read').filter(':last').fadeOut(300, function() {
    if ($(this).is(':last-child')) {
        $('.wrapper').animate({
            height: $('.inner').height()
        }, 300);
    }
});

but I dont know how something like queueAfter could be achieved

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜