jQuery切换点击

cod*_*ude 2 jquery events onclick jquery-animate

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

$('#header .icon').click(function() {
    $('#header form').animate({width:'195px'});
});
Run Code Online (Sandbox Code Playgroud)

但是我怎么做到这一点,当我再次点击该元素时,会发生相反的动画?(例如动画宽度:0px;)

Nic*_*ver 13

你可以.toggle()像这样使用:

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

如果它最初是你可以切换它的宽度像这样:

$('#header .icon').click(function() {
  $('#header form').animate({width:'toggle'});
});
Run Code Online (Sandbox Code Playgroud)


Gás*_*ten 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";
    }
});
Run Code Online (Sandbox Code Playgroud)