Random color table cell background

时间:2015-11-01 01:41:00

标签: javascript html css

I'm trying to give every "td" a different background-color.

My javascript:

var color = '#';
var letters= ['000000','FF0000','00FF00','0000FF','FFFF00','00FFFF','FF00FF','C0C0C0'];
color += letters[Math.floor(Math.random() * letters.length)];
document.getElementById("bg").style.backgroundColor = color;

And my HTML:

<td id="bg">...</td><td id="bg">...</td>

What happens is that every table cell have the same random color, but I need to have them with different color backgrounds.

How can I do it? For loops?

Can you please help me?

3 个答案:

答案 0 :(得分:2)

你不应该在每个td上使用相同的id。如果这些是页面上唯一的td标签,您可以使用以下内容:

var cells = document.getElementsByTagName('td'),
    colors = ['000000','FF0000','00FF00','0000FF','FFFF00','00FFFF','FF00FF','C0C0C0'];

for(var i = 0; i < cells.length; i++) {
    cells[i].style.backgroundColor = '#' + colors[Math.floor(Math.random() * colors.length)];
}

答案 1 :(得分:0)

正如所有人所说,不推荐在多个标签上使用相同的id。但是你可以将所有这些定义为具有相同的类。并在元素上使用jQuery。喜欢这个

<td class="ab">1</td><td class="ab">2</td><td class="ab">3</td>


    var cells = $('td.ab');
    colors = ['000000','FF0000','00FF00','0000FF','FFFF00','00FFFF','FF00FF','C0C0C0'];

    for(var i = 0; i < cells.length; i++) {
        cells[i].style.backgroundColor = '#' + colors[Math.floor(Math.random() * colors.length)];
    }

答案 2 :(得分:0)

所以我可能有点晚了,但是当我手上有太多时间时它做了这个片段,它做了什么:它基本上生成一个表格,并通过随机生成一个十六进制颜色来设置每个单元格的背景生成的字符串 (它还有一个3x3网格悬停在鼠标所在的单元格周围)。

var stringToColour = function(str) {
var hash = 0;
for (var i = 0; i < str.length; i++) {
    hash = str.charCodeAt(i) + ((hash << 5) - hash);
}
var colour = '#';
for (var i = 0; i < 3; i++) {
    var value = (hash >> (i * 8)) & 0xFF;
    colour += ('00' + value.toString(16)).substr(-2);
}
return colour;
}
function makeid() {
  var text = "";
  var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

  for (var i = 0; i < 5; i++)
    text += possible.charAt(Math.floor(Math.random() * possible.length));

  return text;
}

$('#test td').each(function () {
    $(this).css('background-color', stringToColour(makeid()));
});

http://jsfiddle.net/Ltt4hL5x/