如何使用javascript / jquery以数组顺序更改网站的背景?

时间:2015-09-03 15:20:00

标签: javascript jquery css arrays background-color

我希望它也能按顺序改变颜色。该函数应该能够改变给定数组中的背景颜色,每个特定的毫秒数。背景将是蓝色,然后1秒后,黄色,1秒后,粉红色..直到结束阵列的颜色。

bg_changer(colors_TO_change_In_Sequence , 1000);

   var colors_TO_change_In_Sequence = ["blue", "yellow", "pink", "black", "white", "green", "purple", "red", "orange"];

    function bg_changer( color_array , millisecond) {
      $(body).css("background-color", color_array[i]   );
    }

2 个答案:

答案 0 :(得分:1)

您可以使用 setInterval() 来执行功能或重复执行代码段,每次调用该函数之间都会有固定的时间延迟。

var colors_TO_change_In_Sequence = ["blue", "yellow", "pink", "black", "white", "green", "purple", "red", "orange"];
bg_changer(colors_TO_change_In_Sequence, 1000);

function bg_changer(color_array, millisecond) {
  var i = 0;
  setInterval(function() {
    $('#change').css("background-color", color_array[(i++) % color_array.length]);
  }, millisecond);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<div id="change">Change color</div>

答案 1 :(得分:0)

您可以使用setInterval执行此类操作。

&#13;
&#13;
function colorLoop(target, interval, colors){
  // registers the next color's index
  var next = 0;
  function nextColor(){
     // update the div's style
     target.style["background-color"] = colors[next];
     // Goes to next color in the colors' list. Uses modulo to loop.
     next = (next + 1) % colors.length;
  }
  // launch the interval
  setInterval(nextColor, interval);
  // init
  nextColor();
}

colorLoop(
  // the target dom element
  document.getElementsByTagName("body")[0],
  // the change interval in ms
  1000,
  // the colors
  ["blue", "yellow", "pink", "black", "white", "green", "purple", "red", "orange"]
);
&#13;
body {
  transition: 400ms;
}
&#13;
&#13;
&#13;