4

我想要的行为是这样的:背景颜色变为金色,并在 X 时间长度内保持该颜色。然后,背景颜色变为红色,并在 Y 段时间内保持该颜色。然后背景颜色变回金色,并在 X 时间长度内保持该颜色。然后背景颜色变回红色并在 Y 长度内保持这种状态。整个套件和 caboodle 以循环方式执行 Z 次,然后结束。

我尝试将 setInterval 的函数放入 for 循环(以计算我们进行更改的次数),但发现所有已设置为 setInterval 的函数本身都开始运行间隔计时器同时(不按顺序)。

我希望这很清楚。这是我努力的 JSFiddle:http: //jsfiddle.net/6WE6s/3/我已经设法让背景颜色以均匀的方式改变,但我想要上述模式,我很困惑接下来做什么。

在此先感谢您的帮助!:)

4

7 回答 7

2
var colors = [
  ['gold', 2000],  // X = 2000 miliseconds
  ['red', 1000]   // Y = 1000
],
repeat = 3, // Z = 3,
index  = 0, // current position in colors array
changeColor = function( ) {

   // if index == colors.length then mod = 0 
   var mod = index % colors.length;

   if(!index || mod || --repeat ) {
     index = mod;
     var data = colors[ index++  ];  // data = [ currentColor, currentColorTimeout ]
     document.body.style.background = data[0];
     setTimeout( changeColor, data[1] ); // and so on
  }
  //if index >0 && index == last 
  //then decrement `repeat` and check if is == 0
  //nothing to do :)

};
changeColor(); // run

这是一个简单的例子。您可以使用 arguments( colors, repeats) 及其主体来制作函数,如上所示。

注意: setInterval不适合此目的,因为在setInterval您通过超时一次

如果repeat最初为 0 将是无限次重复

于 2012-09-07T06:33:52.320 回答
1

这是我的努力 - 不需要 jQuery:

function colorCycle(el, count, cols) {
    var i = 0,
        n = cols.length;

    // allow this to work on any element given its ID
    el = (typeof el === "string") ? document.getElementById(el) : el;


    if (n === 0) {
        return;       // no colours?
    } else if (n === 1) {
        count = 1;    // don't trigger any timers if there's only one colour
    }

    // all of the hard work is done here
    (function repeat() {

        var interval = cols[i][1];
        el.style.backgroundColor = cols[i][0];

        // only do the whole cycle "count" times - 0 = forever
        if (++i === n) {
            if (count && !--count) {
                return;
            }
            i = 0;
        }
        setTimeout(repeat, interval);  // call myself
    })();  // IIFE starts the cycle straight away
};

colorCycle(document.body, 5, [
    ['red', 1000],
    ['gold', 500]]);

http://jsfiddle.net/alnitak/42PeT/

于 2012-09-07T07:26:46.540 回答
1

不要使用setInterval(). 你setTimeout()可以这样做:

function changeColors(colors, repeats) {
    var i = 0;
    if (typeof repeats === "undefined")
        repeats = 1;
    function doNext() {
        if (i >= colors.length){
            if (--repeats > 0)
                i = 0;
            else
                return;
        }
        $('body').css('background-color', colors[i].color);
        setTimeout(doNext, colors[i++].delay);
    }
    doNext();
}

changeColors([{color : "gold", delay : 2000},
             {color : "red", delay : 4000}],
             3);

您可以添加任意数量的颜色,每种颜色都有自己的延迟,方法是向传递给的数组添加更多元素changeColors()。该函数将依次遍历颜色,并按照repeats参数中指定的次数执行整个序列。

演示:http: //jsfiddle.net/nnnnnn/6WE6s/10/

于 2012-09-07T06:46:27.140 回答
0

尝试这个

var colors = []; 
colors.push({color:"gold", time:4000}); //4000 X length of time
colors.push({color:"red", time:2000}); //2000 Y length of time

var numberofTimes = 50; //50 Z number of times
var $body;
var times = 0; // counter for tracking
var currentColor = {}; //currentColor info can be used to get the current

$(function(){
    $body = $('body');
    changeBG();
});

function changeBG()
{
    currentColor  =  colors[times % colors.length];
    $body.css('background-color',currentColor.color);
    times++;

    if(times<numberofTimes)
       setTimeout(changeBG, currentColor.time);
}

检查这个快速演示

于 2012-09-07T06:32:03.533 回答
0

避免使用 setInterval。参考这里

编辑:我错过了不同的通话延迟。

var colors = ["#FF0000", "#00FF00", "#0000FF"];
var times  = [1000, 2000, 3000];
var backgroundColor = "";
var counter = 0;

var changeBackground = function () {

    // if we ran out of colors — do nothing: this simply goes out
    // of the function, without continually calling setTimeout.
    if (counter >= colors.length)
        return;

    // you fetch your new color here and increase the counter
    // The counter keeps count of how many animations you've done.
    backgroundColor = colors[counter];

    // increase the counter to point to the next index of colors
    // array you'll use in a subsequent call
    counter++;

    // do your magic voodoo change background animation here.
    // I'm just doing a console.log() to be sure this works.
    // Your question was framework agnostic, the answer should be too.
    console.log(backgroundColor);

    // setInterval to repeat
    window.setTimeout(changeBackground, times[counter]);
}

window.setTimeout(changeBackground, times[counter]);
于 2012-09-07T06:35:05.207 回答
0

一个使用 . 迭代颜色数组和时间数组的基本示例setTimeout

(function() {
    var i = 0,
        colorsTimes = [['gold', 'red', 'gold', 'red', 'gold'],
                       [2000, 4000, 2000, 4000, 2000]];

    function switchColors() {
        setTimeout(function() {
            $('body').css('background-color', colorsTimes[0][i]);
            if (++i < colorsTimes[0].length) switchColors();
        }, colorsTimes[1][i]);
    }
    switchColors();
}());

小提琴

于 2012-09-07T06:42:41.263 回答
-1

使用 setTimeout:

var doCount = (function() {
    var count = 0;
    var interval;
    var limit = 5;  // default

    return function(num) {
      limit = num || limit;

      if (count < limit) {
        count++;
        console.log('running number ' + count);
        interval = setTimeout(arguments.callee, 1000);

      } else {
        interval && clearTimeout(interval);
      }
    }

}())

使用 setInterval:

var doCount = (function() {
    var count = 0;
    var interval;
    var limit = 5;  // default

    return function(num) {
      limit = num || limit;

      if (interval) {

        if (++count >= limit) {
          interval && clearInterval(interval);
        }
        console.log('running number ' + count);

      } else {
        interval = setInterval(arguments.callee, 1000);
      }
    }

}())

setTimeout 的优点是您可以调整运行之间的时间以使其更规律,setInterval 只是尝试尽可能规律地运行。

于 2012-09-07T06:39:23.113 回答