2010-08-17 134 views
2

说我需要一个元素来点击时动画。要做到这一点,我只是:jQuery切换点击

$('#header .icon').click(function() { 
    $('#header form').animate({width:'195px'}); 
}); 

但是,我会如何做到这一点,当我再次点击元素相反的动画发生? (如动画,以宽度:0像素;)

回答

13

您可以使用.toggle()这样的:

$('#header .icon').toggle(function() { 
    $('#header form').animate({width:'195px'}); 
}, function() { 
    $('#header form').animate({width:'0px'}); 
}); 

如果是开始出来,你可以切换它的宽度是这样的:

$('#header .icon').click(function() { 
    $('#header form').animate({width:'toggle'}); 
}); 
6

我今天有类似的问题,这里没有答案为我解决它。我的解决方案是为了在点击相同元素时发生不同的事情而保存状态:

var estado="big"; 
$(".snacks").click(function() { 
    if(estado == "big"){ 
     $("#men_snacks").animate({width:"183px", height:"45px"}, 1000); 
     return estado="small"; 
    } else if(estado == "small") { 
     $("#men_snacks").animate({width:"82%",height:"550px"},1000); 
     return estado="big"; 
    } 
});