2010-08-17 217 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"; 
    } 
});