jQuery颜色样式交替

jQuery color style alternating

本文关键字:样式 颜色 jQuery      更新时间:2024-03-28

我正在尝试实现如下jQuery效果:http://jsfiddle.net/Qcghe/1/

$(document).ready(function() {  
    setInterval(function() {
        $('small:nth-of-type(1)')
            .animate( { color: '#F7B903' }, 750)
            .animate( { color: '#FFF' }, 1000); 
    }, 1000);
    setInterval(function() {
        $('small:nth-of-type(2)')
            .animate( { color: '#5BB6FD' }, 750)
            .animate( { color: '#FFF' }, 1000); 
    }, 2000);
    setInterval(function() {
        $('small:nth-of-type(3)')
            .animate( { color: '#D13360' }, 750)
            .animate( { color: '#FFF' }, 1000); 
    }, 3000);
});

我想按以下顺序设置点的颜色动画:

  1. 白色,白色,白色(初始状态)
  2. 蓝色、白色、白色
  3. 蓝色、红色、白色
  4. 蓝色、红色、绿色
  5. 白色、红色、绿色
  6. 蓝色、白色、绿色
  7. 蓝色、红色、白色
  8. …然后回到初始状态

我在Photoshop中制作了一个动画GIF来帮助说明(黑白颠倒):

gif动画http://cdn.vpsunder10.com/1.gif

检查代码

$(document).ready(function() {  
  setInterval(function() {
    $('small:nth-of-type(1)')
    .animate( { color: '#F7B903' }, 1000)
    .delay(4000)
    .animate( { color: '#FFF' }, 1000); 
     $('small:nth-of-type(2)')
    .delay(1000)
    .animate( { color: '#5BB6FD' }, 1000)
    .delay(5000)
    .animate( { color: '#FFF' }, 1000); 
      $('small:nth-of-type(3)')
    .delay(2000)
    .animate( { color: '#D13360' }, 1000)
    .delay(6000)
    .animate( { color: '#FFF' }, 1000); 
    }, 10000);
 });

http://jsfiddle.net/Qcghe/3/

因为它们每个都遵循一个相似但相关的动画循环,所以我会尝试将其表示为一个步骤序列,而不是三个单独的步骤。

var $dots = $('#dots span'),
    colors = ['blue', 'red', 'green'], // Colour assigned to each dot, in order.
    step = 1000;                       // Duration of each animation step in ms.
function cycle() {
    $dots
        .finish() // Ensure no animations still running from last cycle.
        .each(function(index, dot) {
            var $dot = $(dot),
                color = colors[index];
            $dot
                .delay(index * step)
                .animate({ color: color }, step)
                .delay(step * 2)
                .animate({ color: 'white' }, step)
                .promise()
                .done(function() {
                    // All but last should be restored to dot colour.
                    if (index != 2) $dot.animate({ color: color }, step);
                })
            ;
        });
    // Set all the dots to white once animations have finished.
    $dots.promise().done(function() { $dots.animate({ color: 'white' }, step) });
}
// Start immediately, and thereafter every seven steps.
cycle();
setInterval(cycle, step * 7);

jsFiddle演示

您可以通过使用step变量使其更快或更慢。

(如果你感兴趣并且不必支持旧的浏览器,我也可以向你展示如何在带有关键帧动画的纯CSS中做到这一点。)