如何制作一个jquery无限动画?

Mau*_*o74 18 jquery loops jquery-animate

我正在尝试使用无限循环实现jQuery函数,以使用3种颜色为主体背景设置动画.我想不出一个漂亮而干净的解决方案.像这样的东西?

$(document).ready(function(){                
     $('body').animate({backgroundColor:'#ffcc00'}, 500, function(){
        $('body').animate({backgroundColor:'#eeeeee'}, 500, function(){
           $('body').animate({backgroundColor:'#3b5998'}, 500);
       });
   });
});
Run Code Online (Sandbox Code Playgroud)

任何的想法?

Ces*_*sar 21

$(document).ready(function(){
    function animate() {
        $('body').animate({backgroundColor:'#ffcc00'}, 500, function(){
            $('body').animate({backgroundColor:'#eeeeee'}, 500, function(){
                $('body').animate({backgroundColor:'#3b5998'}, 500, function(){
                    animate();
                });
            });
        });
    }
    animate();
});
Run Code Online (Sandbox Code Playgroud)

  • 一段时间后,这不会导致堆栈溢出(没有双关语)吗? (7认同)
  • 好点,@ AndyHin!最初我的想法是一样的,但答案是:没有.这是因为.animate()将动画添加到动画队列中(连同关于在完成时应该调用哪个函数的信息)以及立即执行代码继续下一个声明. (4认同)

Dio*_*ane 11

你可以消除嵌套,但解决方案有点胖:

var cols = "#ffcc00,#eeeeee,#3b5998".split(",")
var cPos = 0

$(document).ready(function() {
   swapC()
}    

function swapC() {
    $('body').animate({ backgroundColor:cols[cPos] }, 500)
    cPos++
    if (cPos == cols.length) {
        cPos = 0
    }
    window.setTimeout(function() { swapC() }, 500)
}
Run Code Online (Sandbox Code Playgroud)

  • 不要使用超时(这是不可靠的),而是使用`animate()`回调函数.你冒着竞争的风险. (8认同)

fit*_*rec 8

$(document).ready(function(){
    colors = ['#FFB30C', '#58EC00', '#0087EC', '#EEEEEE', '#FF5A00' ]
    var i = 0;
    animate_loop = function() {
            $('body').animate({backgroundColor:colors[(i++)%colors.length]
            }, 500, function(){
                        animate_loop();
            });
    }
    animate_loop();
});
Run Code Online (Sandbox Code Playgroud)

演示:http://jsfiddle.net/bHEVr/


lin*_*abá 7

$(".elementsToAnimate").each(function setAnim(){
    $(this).
            animate({backgroundColor:'#ffcc00'},500).
            animate({backgroundColor:'#eeeeee'},500).
            animate({backgroundColor:'#3b5998'},500,setAnim);
});
Run Code Online (Sandbox Code Playgroud)


小智 5

我宁愿使用事件驱动的方法:

$(document).ready(function(){
  $('body').on('color1', function () {
    $(this).animate({backgroundColor:'#ffcc00'}, 500, function(){
      $(this).trigger('color2');
    });
  });

  $('body').on('color2', function () {
    $(this).animate({backgroundColor:'#eeeeee'}, 500, function(){
      $(this).trigger('color3');
    });
  });

  $('body').on('color3', function () {
    $(this).animate({backgroundColor:'#3b5998'}, 500, function(){
      $(this).trigger('color1');
    });
  });

  // Kick-off the infinite loop by firing one of the events
  $('body').trigger('color2');
});
Run Code Online (Sandbox Code Playgroud)

观看此解决方案的实际应用:

http://jsfiddle.net/perituswebdesign/f5qeo6db/1/