我正在尝试创建一个类似于这个的表:
我上传了网站,因此可以在此处查看:http://alainwebdesign.ca/CIS245/rgb.html
在脚本文件中,我试图填充" Red Hex "列修改generateRandomReds()
函数,如下所示:
function generateRandomReds(){
for(var i=0; i<11; i++){
var randRed = Math.random();
randRed = randRed.toFixed(2);
var sel = document.getElementById('genRandomReds');
var opt = document.createElement('option');
opt.innerHTML = randRed;
opt.value = randRed;
sel.appendChild(opt);
//Trying to convert decimal to hex and populate the "Red Hex"
//column in the Generate random colors table
//but for some reason adding this code makes it so only 1 random
//red decimal value is created and that's it:
var selHex = document.getElementById('genRedHex');
var optHex = document.createElement('option');
optHex.innerHTML = randRed(parseInt( number , 10)).toString(16);
optHex.value = randRed(parseInt( number , 10)).toString(16);
selHex.appendChild(optHex);
}
}
答案 0 :(得分:0)
A创建了以下代码来解释:
HTML:
<button type="button" class="btn btn-default" id="generate-btn">Genarate Random Colors</button>
<br/><br/>
<table class="table">
<thead>
<tr>
<th>RGB Values</th>
<th>RGH Hexadecimal Values</th>
<th>Display</th>
</tr>
</thead>
<tbody id="tbody">
</tbody>
</table>
使用Javascript:
document.getElementById('generate-btn').addEventListener("click", generateRandom);
var tbody = document.getElementById('tbody');
function generateRandom() {
tbody.innerHTML = '';
for (var i = 0; i < 11; ++i) {
var randR = (Math.random().toFixed(3) * 1000) % 256;
var randG = (Math.random().toFixed(3) * 1000) % 256;
var randB = (Math.random().toFixed(3) * 1000) % 256;
var rgbValue = '(' + randR + ', ' + randG + ', ' + randB + ')';
var tdF = '<td>' + rgbValue + '</td>';
var hexValue = '#' + randR.toString(16) + randG.toString(16) + randB.toString(16);
var tdH = '<td>' + hexValue + '</td>';
var display = '';
var tdD = '<td style="background-color:' + hexValue + '"></td>';
var tr = '<tr>' + tdF + tdH + tdD + '</tr>'
tbody.innerHTML = tbody.innerHTML + tr;
}
}
在这个例子中,我生成整数RBG数。 RGB从0到255,因此创建的随机数为3位,最大值为255。 要转换为十六进制,只需使用toString(16)。