首先,我正在尝试使用javascript课程,所以请注意我对其语法的理解仍然有限。
我需要创建一个包含28种随机颜色的表格,然后每按一下按钮就可以更新它。我想在与按钮相同的页面上创建表,但是我在使用document.write时似乎只能使用它,然后将其写入带有表的新页面。
任何帮助清理我的代码将不胜感激。谢谢!
<head>
<title>Random Color Generator</title>
</head>
<body>
<h2>Random World Generator</h2>
<button id="rcg_generate_button" onclick="rcg_generate()">Generate</button>
<script type="text/javascript">
// Counters
var i = 0;
var j = 0;
var k = 0;
var x = 0;
var y = 0;
var z = 0;
// Define range for percentage of color
var min = 0;
var max = 5;
// RGB values
var r;
var g;
var b;
//Misc Vars
var color;
var display_color;
var stored_colors = new Array();
var shades = new Array('00','33','66','99','CC','FF');
//Generate Color Table
function rcg_generate() {
while (i <= 27) {
r = Math.round(Math.random() * (max-min) + min);
g = Math.round(Math.random() * (max-min) + min);
b = Math.round(Math.random() * (max-min) + min);
color = shades[r] + shades[g] + shades[b];
stored_colors[i] = color;
i++;
}
document.write('<table cellspacing="0" id="grid">');
for (k = 0; k <= 3; k++) {
document.write('<tr>');
for (j = 0; j <= 6; j++) {
display_color = stored_colors[x]
document.write('<td style="background: #'+display_color+'; height: 30px; width: 75px;">');
document.write('<p align = "center">'+display_color+'<\/p>');
document.write('<\/td>');
x++;
}
document.write('<\/tr>');
}
document.write('<\/table>');
}
</script>
</body>
</html>
答案 0 :(得分:1)
用HTML构建表格,然后在JS中选择所有td
元素并更改其背景颜色:
function colors () {
[].slice.call (document.querySelectorAll ('#colors td')). forEach (function (tdEl) {
var r = Math.round (Math.random () * (max - min) + min),
g = Math.round (Math.random () * (max - min) + min),
b = Math.round (Math.random () * (max - min) + min);
tdEl.style.backgroundColor = '#' + shades[r] + shades[g] + shades[b];
});
}
button.addEventListener ('click', colors, false);
上的演示