Jquery 动画功能的切换动作

Jquery toggle action for animate function

我需要 link jQuery 一起切换和动画功能。当我点击框时,它的大小应该改变。我的代码 js fiddles 片段在这里。为什么它不起作用?它在启动时消失。

JS Fiddle snip

$(document).ready(function() {
$('.adiv').toggle(
   function(){
        $(this).animate({
            width: "150",
            height: "150",
        }, 1000);
    },
    function(){
        $(this).animate({
            width: "77", 
            height: "77",
        }, 1000);        
});
});

Toggle 将 hide/show 你的元素,因为你的元素在初始加载时可见,第一次调用你的切换函数时它会动画,但随后切换将在元素上设置显示 none导致它隐藏起来。你不应该为此使用切换功能。

你应该使用这样的东西:

$(document).ready(function() {
    var big = false;
    $('.adiv').on('click', function(){
        if( big ) {
             $(this).animate({
                    width: "77", 
                    height: "77",
                }, 1000);        
        } else {
            $(this).animate({
                    width: "150",
                    height: "150",
                }, 1000); 
        }
        big = !big;
    });
});

这是一个工作示例:http://jsfiddle.net/x7f34vr5/1/

您需要指定一个点击处理程序,否则它会立即 运行。例如

$('.adiv').click( function () {
// Do stuff here
});

切换和动画并不能真正结合在一起 - 这是一种不同的方式:

$(document).ready(function () {
    $('.adiv').click( function () {
        var newSize = $(this).width() > 77 ? 77 : 150;

        $(this).animate({
            width: newSize,
            height: newSize,
        }, 1000);
    });
});

Fiddle here.