开发者

Passing DOM object dynamically in jQuery.animate

开发者 https://www.devze.com 2023-03-17 02:36 出处:网络
I am using jQuery .animate method to animate a stack of cards. Assuming these are the four cards visually displayed [#card1][#card2][#card3][#card4][#card5]

I am using jQuery .animate method to animate a stack of cards. Assuming these are the four cards visually displayed [#card1][#card2][#card3][#card4][#card5]

Their div tags , #card1 , #card2, #card3 , #card4 are stored in an array cardStack() Now i want to animate each of these on click, one after the other when you click them. So can i do something like

while(cardSt开发者_如何转开发ack[0]!="undefined"){
    $('#cardStack[0]').click(function() {    
    $('#cardStack[0]').animate({"left": "+=130px","z-index": "1",queue:false},500);
});
i--;
}

is this possible ?


I'll annotate the source, so that you could actually learn something:

Save the reference to the array of cards.

var cards = $('#cards div');

The first flipped card will be outside our array.

var flippedIndex = cards.length;

Next, we create an array (with the same length as the cards array), containing information on which cards are flipped.

var flipped = new Array(flippedIndex);

The flip function animates and changes the class attribute of a card.

var flip = function (card, toggle) {
    card.slideUp(function () {
        card.toggleClass('back', toggle)
            .slideDown();
    });
};

Now we set the click listener.

cards.click(function () {
    var card = $(this),

.index() (http://api.jquery.com/index/) gives you the position of the card from left to right.

    index = card.index();

Lookup our flipped array to see if the card is flipped and check that it's the last card flipped.

if (!flipped[index] && index + 1 === flippedIndex) {
        flippedIndex = index;

Here we flip the card.

    flip(card, (flipped[index] = true));
} else if (flipped[index] && index === flippedIndex) {
    flippedIndex++;

Here we unflip it.

       flip(card, (flipped[index] = false));
    }
});
0

精彩评论

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