我在页面上有一系列 DIV(每个都有相同的类)。在加载时,我想随机化每个 DIV 的颜色。
我想为给定的 DIV 选择一种颜色,然后为下一个选择颜色,依此类推。
我找到了这篇文章:Apply random color to class elements individually?
我不懂 jquery,但是我已经开始更改代码以反射(reflect)我正在使用的类的名称:
$(document).ready(function() {
$('.main').each(function () {
var hue = 'rgb(' + (Math.floor((256-199)*Math.random()) + 200) + ',' + (Math.floor((256-199)*Math.random()) + 200) + ',' + (Math.floor((256-199)*Math.random()) + 200) + ')';
$(.jump-response).css("background-color", hue);
});
});
我们将不胜感激!
--
此处的代码示例:http://jsfiddle.net/ollyf/LmwYP/
我还应该添加来自预设/预定颜色列表的随机背景颜色。
最佳答案
我不知道你的 html,但假设你的 div 定义如下。
<div class="jump-response">one</div>
<div class="jump-response">two</div>
代码中的主要问题是如何选择元素。
1。解决方案
$(function() {
$(".jump-response").each(function() {
var hue = 'rgb(' + (Math.floor((256-199)*Math.random()) + 200) + ',' + (Math.floor((256-199)*Math.random()) + 200) + ',' + (Math.floor((256-199)*Math.random()) + 200) + ')';
$(this).css("background-color", hue);
});
});
jsFiddle Demonstration
2。解决方案
您可以使用以下函数来获得随机颜色
function get_random_color() {
var letters = '0123456789ABCDEF'.split('');
var color = '#';
for (var i = 0; i < 6; i++ ) {
color += letters[Math.round(Math.random() * 15)];
}
return color;
}
并应用颜色
$(".jump-response").each(function() {
$(this).css("background-color", get_random_color());
});
jsFiddle Demonstration
关于jquery - 将随机背景颜色应用于多个 DIV,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10540301/