在多个类的单个实例上切换动画

时间:2014-01-07 22:38:14

标签: jquery css animation onclick toggle

the community的帮助下,我设法解决了多次出现的类的单个实例而不影响其他类。谢谢!

<div class="trigger">
   <p class="mover"> some content </p>
/div>

<div class="trigger">
   <p class="mover"> some content </p>
/div>

我现在要做的是为这个单个实例切换动画。 当点击“trigger-”div时,我希望它的孩子(移动者)向右移动。 这似乎有效。

不起作用是指在切换上一个动画之前单击下一个触发器。原因很明显,我猜(存储的变量不会被设置回来),但我不知道如何做到这一点。

var state="on";
$('.trigger').click(function() {
    if(state == "on"){
         $(this).children(".mover").animate({'margin-right': '-=40px'},'fast'); 
        return state="off";
    } else if(state == "off") {
         $(this).children(".mover").animate({'margin-right': '+=40px'},'fast');
        return state="on";
    }
});

非常感谢!

1 个答案:

答案 0 :(得分:0)

state存储在每个.data()的{​​{1}}中:

.trigger

或更有效率:

$('.trigger').data('state','on').click(function() {
    if($(this).data('state') == "on"){
         $(this).children(".mover").animate({'margin-right': '-=40px'},'fast'); 
        $(this).data('state','off');
    } else if($(this).data('state') == "off") {
         $(this).children(".mover").animate({'margin-right': '+=40px'},'fast');
        $(this).data('state','on');
    }
});