jQuery动画切换 [英] jQuery Animation Toggle

查看:83
本文介绍了jQuery动画切换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个非常简单的问题.我基本上在页面上有一个div块,当单击该块时,其大小会增大,而再次单击时,该块会返回原来的状态.我的问题是它似乎根本不起作用.另外,我敢肯定有比这样的if语句更干净的方法来切换两个动画状态,但是我不确定该怎么做.

This is a pretty straight-forward problem. I basically have a div block on a page that, when clicked, grows in size, and when clicked again returns back to what it was. My problem is that it just doesn't seem to work at all. Plus, I'm sure there is a much cleaner way to toggle between two animation states than an if statement like this, but I'm not sure how exactly to go about doing that.

$(document).ready(function(){
    var toggle = 0;
    $(".login").click(function(){
        if($toggle == 0){
            $(this).animate({
                height: '200',
            }, 500, function(){
            });
            $toggle = 1;
        }
        else if($toggle == 1){
            $(this).animate({
                height: '100',
            }, 500, function(){
            });
            $toggle = 0;
        }
    });
});

相应的html代码很简单

Corresponding html code is simply

<div class="login">Click Me</div>

让我知道是否还需要其他任何东西.

Let me know if anything else is needed.

推荐答案

您的代码无法正常工作,因为您在一个地方使用了toggle而在另一个地方使用了$toggle.

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'});
    });​
});

在此处工作的演示: http://jsfiddle.net/jfriend00/5Wu6m/

给定一系列函数作为参数时,.toggle(fn1, fn2)方法将在从第一个函数开始的给定函数之间交替.这样会自动为您跟踪切换状态-您不必这样做.

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文档位于此处. .toggle()有多种形式,具体取决于所使用的参数,因此在搜索jQuery文档时并不总是找到正确的形式.

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.

这篇关于jQuery动画切换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆