使用圆中的数组更改背景颜色项目

Changing background colors items using an array in a circle

本文关键字:背景 颜色 项目 数组      更新时间:2023-09-26

我有一个特殊的挑战,正在扼杀我,因为我不知道如何做我想做的事。

我有5个项目:4个div,宽度和高度分别为50px和正文。

我想创建一个函数来设置这些项目的背景颜色,例如:

var colors = ['red', 'blue', 'green', 'black', 'pink'];
div1 = red
div2 = blue
div3 = green
div4 = black
body = pink

如果浏览器重新加载,它们就会改变:

div1 = pink
div2 = red
div3 = blue
div4 = green
body = black

如果浏览器发生同样的变化。。。

有任何jquery插件可以做到这一点吗?我不知道从哪里开始。。我已经在一个函数中创建了带有项的数组:

HTML:

<body>
 <div></div>
 <div></div>
 <div></div>
 <div></div>
</body>

JS:

function changeColors() {
    var colors = ['red', 'blue', 'green', 'black', 'pink'];

}
changeColors();

您可以使用以下函数随机洗牌数组:

<script type="text/javascript">
function shuffle(array) {
  var currentIndex = array.length, temporaryValue, randomIndex ;
  // While there remain elements to shuffle...
  while (0 !== currentIndex) {
    // Pick a remaining element...
    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex -= 1;
    // And swap it with the current element.
    temporaryValue = array[currentIndex];
    array[currentIndex] = array[randomIndex];
    array[randomIndex] = temporaryValue;
  }
  return array;
}
</script>

这就是如何应用它:

<script type="text/javascript">
var colors = ['red', 'blue', 'green', 'black', 'pink'];
shuffle(colors);
// and your code to assign colors to divs and body
</script>

如果希望每次加载页面时更改值,则需要使用localStorage或cookie。以下是使用localStorage:的示例

var colors = ['red', 'blue', 'green', 'black', 'pink'];
if(localStorage.count)
{
    localStorage.count = (localStorage.count + 1) % colors.length;
}
else
{
    localStorage.count = 0;
}
for(var i = 0; i < colors.length; i++)
{
    var color = colors[(localStorage.count + i) % colors.length];
    //Set the i'th element's back-color to color
}

这里有一个Fiddle,展示了模方法如何工作的例子

这应该是一项非常简单的任务

var colors = ['red', 'blue', 'green', 'black', 'pink'];
var count = 0;
function colorMe() {
  $("body").find("div").each(function() {
    var index = $("body").find("div").index(this);
    var i = (index + count) % colors.length;
    $(this).css("background-color", colors[i]);
  });
  count++;
}
$(window).resize(colorMe);
$(document).ready(colorMe);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>first</div>
<div>second</div>
<div>third</div>
<div>fourth</div>

我认为你的主要问题是确定使用了什么浏览器,所以你可以阅读以下内容:如何检测Safari、Chrome、IE、Firefox和Opera浏览器?然后你可以开始制作代码,根据浏览器的不同来更改颜色。我希望这就是答案。