问题
Say I need an element to animate when clicked. To do this I just:
$('#header .icon').click(function() {
$('#header form').animate({width:'195px'});
});
But how would I make it so that when I click the element again the opposite animate takes place? (e.g. animate to width: 0px; )
回答1:
You can use .toggle() like this:
$('#header .icon').toggle(function() {
$('#header form').animate({width:'195px'});
}, function() {
$('#header form').animate({width:'0px'});
});
If it was initially out you could toggle it's width like this:
$('#header .icon').click(function() {
$('#header form').animate({width:'toggle'});
});
回答2:
I had a similar problem today, and none of the answers here solved it for me. My solution was to save states in order to have different things happen when the same element is clicked:
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";
}
});
来源:https://stackoverflow.com/questions/3505323/jquery-toggle-click