改进这个连续的jQuery动画

Mar*_*rko 3 jquery animation continuous effect

我刚刚在jQuery中创建了一个简单,连续的反弹效果,但我觉得代码并非全部优化,我希望改进它.

var $square = $("#square");
bounce();
function bounce() {
    $square.animate({
        top: "+=10"
    }, 300, function() {
        $square.animate({
            top: "-=10"
        }, 300, function() {
            bounce();
        })
    });
}

$square.hover(function() {        
    jQuery.fx.off = true;
}, function() {
    jQuery.fx.off = false;
});
Run Code Online (Sandbox Code Playgroud)

我所做的一切基本上是创建了一个动画,它将+10添加到元素的顶部坐标,作为回调函数,我从顶部坐标减去10 ..

这会产生(几乎光滑)弹跳效果,但我觉得它可以改进.

此外,我想停止动画mouseenter,并继续mouseleave.

stop(true, true)没有工作,也没有dequeue()这样做我已经使用jQuery.fx.off = true(愚蠢,没有?)关闭所有动画效果

我很感激有关如何优化这些的任何反馈.

这是一个jsFiddle.

编辑:我刚刚意识到jQuery too much recursion在禁用和重新启用效果时已经开始抛出错误.

提前致谢,

马尔科

小智 7

请尝试以下代码演示:http://jsfiddle.net/LMXPX/

$(function() {
    var $square = $("#square"),flag = -1;
    var timer = bounce = null;
    (bounce = function () {
        timer = setInterval(function() {
            flag = ~flag + 1;
            $square.animate({ 
                top: "+="+(flag*10)
            }, 300)
        },300);
    })();                
    $square.hover(function() {        
        clearInterval(timer);
    }, function() {
        bounce();
    });
});
Run Code Online (Sandbox Code Playgroud)

编辑:我猜你的代码中有多个CallBack函数是递归过多的原因