在jQuery动画中编写匿名函数

时间:2013-06-21 09:45:58

标签: jquery jquery-animate

请帮我写动画中的匿名函数,我已经给出了我试过的代码,这是DEMO,我想知道如何在动画中编写匿名函数,就像我在做的那样点击Css按钮,提前谢谢

<html>
    <head>
        <title></title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> 
        <style type="text/css">
           #example{width:100px;height:100px;background: #F00;}
        </style>
        <script>
            $(document).ready(function(){
                $('#check').click(function(){
                    $('#example').css({width:function(){
                            console.log($(this).width());
                            return $(this).width()=="0"? "100":"0";
                    }});
                });
                $('#animate').click(function(){
                    $('#example').animate({width:function(){
                            console.log($(this).width());
                            return $(this).width()=="0"? "100":"0";
                    }});
                });
            });
        </script>
    </head>
    <body>
        <div id="example">            

        </div>
        <input type="button" value="Css" id="check"/>
        <input type="button" value="Animate" id="animate"/>
    </body>
</html>

1 个答案:

答案 0 :(得分:1)

Demo

$('#animate').click(function () {
    $('#example').animate({
        width: (function ($self) {
            console.log($self.width());
            return $self.width() == "0" ? "100" : "0";
        })($('#example'))
    });
});