Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/68.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 给定颜色数组的颜色元素_Javascript_Jquery - Fatal编程技术网

Javascript 给定颜色数组的颜色元素

Javascript 给定颜色数组的颜色元素,javascript,jquery,Javascript,Jquery,如何将此颜色数组分配给一组div var colors = ['#2d335b', '#535b2d', '#494949', '#d7d7d7', '9ad4ce']; 我知道我可以从数组中随机选择颜色,如下所示: var random_color = colors[Math.floor(Math.random() * colors.length)]; $("div").css('background-color', random_color); 但是它使用了很多相同的颜色来排列,我需要它

如何将此颜色数组分配给一组div

var colors = ['#2d335b', '#535b2d', '#494949', '#d7d7d7', '9ad4ce'];
我知道我可以从数组中随机选择颜色,如下所示:

var random_color = colors[Math.floor(Math.random() * colors.length)];
$("div").css('background-color', random_color);

但是它使用了很多相同的颜色来排列,我需要它们更分散。如何按顺序分配它们,从数组中的第一种颜色开始到最后一种颜色,然后返回到第一种颜色?

实际上,可以使用范围内的值步骤来防止两种颜色接近。要执行您要求的操作,您可以设置currentColor值,并在每次设置颜色时增加该值。使用数组中的元素(而不是随机数)时,可以使用currentColor作为索引。然后可以根据数组长度修改结果,使其循环

var currentColor=0;
var colorArray=[1,2,3,4,5,6];

对于(var i=0;i,您可以通过循环元素和按列表长度对索引进行模块化来完成它

var colors = ['#2d335b', '#535b2d', '#494949', '#d7d7d7', '9ad4ce'];
var divs = $('div');


for (var i = 0; i < divs.length; i++) {
    var color = colors[i % colors.length];

    $(divs[i]).css('background-color', color);
};
div{
宽度:50px;
高度:50px;
边缘底部:0.5em;
边框:1px实心#000;
}


出错“TypeError:divs[1]。css不是一个函数。你能做一个JS小提琴吗?我的错,把
divs[i]
替换成
$(divs[i])
我能在for循环中将currentColor变量应用到我的div的css吗?我是初学者,请说明我将如何在我的问题上下文中应用你的代码(对一组div应用不同的颜色)。
var colors = ['#2d335b', '#535b2d', '#494949', '#d7d7d7', '9ad4ce'];

// selecting the <div> elements, and chaining with the css()
// method; using that method to update the specified -
// 'background-color' - property using the anonymous function
// from which we use the index of the <div> in from the jQuery
// collection:
$('div').css('background-color', function (index) {

  // using the index to determine which color should
  // be retrieved, and returning it as the value
  // to set as the background-color. This approach
  // iterates over each element in the collection
  // and returns the appropriate value to each of
  // those elements:
  return colors[index % colors.length];
});