jQuery Animation Toggle

我的未来我决定 提交于 2019-12-04 18:11:45

Your code isn't working because you have used toggle in one place and $toggle in another.

But, this can be done more simply like this:

$(document).ready(function(){
    $(".login").toggle(function() {
        $(this).animate({height: '200'});
    }, function() {
        $(this).animate({height: '100'});
    });​
});

Working demo here: http://jsfiddle.net/jfriend00/5Wu6m/

When given a list of functions as arguments, the .toggle(fn1, fn2) method will alternate between the functions given starting with the first one. This automatically keeps track of the toggle state for you - you don't have to do that.

jQuery doc is here. There are multiple forms of .toggle() depending upon the arguments used so you don't always find the right one when searching the jQuery doc.

Notice the difference between

var toggle = 0;

and

if($toggle == 0){

You define a variable named toggle, then use it as $toggle.

Try

$(".login").click(function(){
    $(this).slideToggle(500);
}

Two problems I see. One is the scope of your toggle variable. The other is the common after the single attribute in your animation attribute list. Try this:

$(document).ready(function(){
    $(".login").click(function(){
        if($(this).hasClass('expanded')){
            $(this)
                .removeClass('expanded')
                .stop()
                .animate({height: '100px'}, 500)
            ;   
        }
        else{
            $(this)
                .addClass('expanded')
                .stop()
                .animate({height: '200px'}, 500)
            ;                
        }
    });
});
var H=H==200?100:200;
$(".login").on('click', function(){
    $(this).animate({height: H}, 500, function() {H=H==200?100:200;});
});

FIDDLE

I want to defend your toggle solution, it isn't incorrect.

In some case only this way of code will work correct, while .toggle() will do some weird things.

Only instead of if($toggle == 0){... you need use if ( toggle === 0 ){

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