jQuery toggle click

青春壹個敷衍的年華 提交于 2019-12-06 10:11:56

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!