【问题标题】:Improving this continuous jQuery animation改进这个连续的 jQuery 动画
【发布时间】:2011-04-06 11:14:09
【问题描述】:

我刚刚在 jQuery 中创建了一个简单、连续的 bounce effect,但我觉得代码并没有那么优化,我希望对其进行改进。

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

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

这会产生(几乎平滑的)反弹效果,但我觉得可以改进。

此外,我想在mouseenter 上停止动画,并让它在mouseleave 上继续播放。

stop(true, true) 不起作用,dequeue() 也不起作用,所以我求助于使用 jQuery.fx.off = true 关闭所有动画效果(愚蠢,不是吗?)

如有任何关于如何优化的反馈,我将不胜感激。

这是jsFiddle

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

提前致谢,

马尔科

【问题讨论】:

  • 我猜,通过在自身内部调用bounce() 作为回调,会生成一个很大的堆栈跟踪,从而导致太多的递归错误。
  • 递归太多的问题是递归太多了。
  • 是的@Neil - 为了理解递归,你必须首先理解递归。

标签: jquery animation effect continuous


【解决方案1】:

请尝试以下代码演示: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();
    });
});

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

【讨论】:

  • 那么在没有回调的情况下,还有其他方法可以连续循环动画吗?
  • 头疼 抱歉,现在是上午 9 点,我刚起床 :) 效果很好,可以接受。
【解决方案2】:

没有太大的改进,但这是我的尝试:

var $square = $("#square");

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

$square.hover(function() {
    $.fx.off = !$.fx.off;
});

【讨论】:

  • 一开始也想写同样的代码,但是导致递归太多,callBack函数就是递归太多的原因:(
猜你喜欢
  • 2011-10-06
  • 2014-05-16
  • 2012-09-23
  • 1970-01-01
  • 2013-01-18
  • 2011-06-25
  • 1970-01-01
  • 2011-12-19
  • 2023-03-24
相关资源
最近更新 更多