通过jquery给出随机的css syle

时间:2017-12-18 20:42:25

标签: jquery

我希望使用此代码为每个div标记随机提供背景颜色。但它会将所有div标记设置为一种背景颜色。我希望他们与众不同。它曾经正常工作,但发生了一些事情,它现在不起作用:



var downcolors = ["#ff7043", "#8d6e63", "#ffa726", "#ffca28", "#66bb6a", "#9ccc65", "#d4e157", "#29b6f6", "#26c6da", "#26a69a", "#4db6ac", "#4dd0e1", "#4fc3f7", "#009688", "#7e57c2", "#5c6bc0", "#42a5f5", "#ef5350", "#ec407a", "#ab47bc"];
var topcolors = ["#d84315", "#37474f", "#455a64", "#d84315", "#bf360c", "#3e2723", "#4e342e", "#5d4037", "#212121", "#424242", "#1b5e20", "#33691e", "#827717", "#01579b", "#006064", "#004d40", "#6200ea", "#311b92", "#1a237e", "#0d47a1", "#4527a0", "#283593", "#b71c1c", "#880e4f", "#4a148c"];
var downrand = Math.floor(Math.random() * downcolors.length);
var toprand = Math.floor(Math.random() * topcolors.length);

$.each($(".tg-item-inner"), function(idx, elem) {
  $(elem).css({
    'background': 'linear-gradient(to top, ' + downcolors[downrand] + ' 50%, ' + topcolors[toprand] + ' 50%)'
  });
});




1 个答案:

答案 0 :(得分:1)

每次循环时都需要更改随机变量,即循环内部而不是外部:



var downcolors = ["#ff7043", "#8d6e63", "#ffa726", "#ffca28", "#66bb6a", "#9ccc65", "#d4e157", "#29b6f6", "#26c6da", "#26a69a", "#4db6ac", "#4dd0e1", "#4fc3f7", "#009688", "#7e57c2", "#5c6bc0", "#42a5f5", "#ef5350", "#ec407a", "#ab47bc"];
var topcolors = ["#d84315", "#37474f", "#455a64", "#d84315", "#bf360c", "#3e2723", "#4e342e", "#5d4037", "#212121", "#424242", "#1b5e20", "#33691e", "#827717", "#01579b", "#006064", "#004d40", "#6200ea", "#311b92", "#1a237e", "#0d47a1", "#4527a0", "#283593", "#b71c1c", "#880e4f", "#4a148c"];

$.each($("div"), function(idx, elem) {
  // move random variables to inside the loop
  var downrand = Math.floor(Math.random() * downcolors.length);
  var toprand = Math.floor(Math.random() * topcolors.length);
  $(elem).css({
    'background': 'linear-gradient(to top, ' + downcolors[downrand] + ' 50%, ' + topcolors[toprand] + ' 50%)'
  });
});

div {
  width: 100px;
  height: 100px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
&#13;
&#13;
&#13;