jQuery 切换点击
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3505323/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery toggle click
提问by codedude
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; )
但是我将如何做到这一点,以便当我再次单击该元素时会发生相反的动画?(例如动画宽度:0px;)
回答by Nick Craver
You can use .toggle()
like this:
你可以这样使用.toggle()
:
$('#header .icon').toggle(function() {
$('#header form').animate({width:'195px'});
}, function() {
$('#header form').animate({width:'0px'});
});
If it was initiallyout you could toggle it's width like this:
如果它最初出来,你可以像这样切换它的宽度:
$('#header .icon').click(function() {
$('#header form').animate({width:'toggle'});
});
回答by Gásten
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";
}
});