我一直在尝试将div的颜色更改为随机生成的十六进制颜色代码,该代码被传递到变量中。我该如何完成这项工作?
.HTML
<p id="demo">NULL</p>
<button onclick="generatePassword()">Generate</button>
<div id="showcase" style="background: #FFFFFF; width: 200px; height: 200px; margin: 20px; border-radius: 3px;"></div>
JAVASCRIPT
var result = document.getElementById('demo').innerHTML;
function generatePassword() {
var length = 6,
charset = "ABCDEF0123456789",
retVal = "";
for (var i = 0, n = charset.length; i < length; ++i) {
retVal += charset.charAt(Math.floor(Math.random() * n));
}
document.getElementById('demo').innerHTML = "#" + retVal;
return document.getElementById('showcase').style.backgroundColor = retVal;
}
链接到小提琴:https://jsfiddle.net/elliotsoomro/gngg89t5/5/
你几乎得到了它,这是修复:https://jsfiddle.net/yL1uu6bz/1/
var result = document.getElementById('demo').innerHTML;
function generatePassword() {
var length = 6,
charset = "ABCDEF0123456789",
retVal = "";
for (var i = 0, n = charset.length; i < length; ++i) {
retVal += charset.charAt(Math.floor(Math.random() * n));
}
var finalVal = "#" + retVal;
document.getElementById('demo').innerHTML = finalVal;
return document.getElementById('showcase').style.backgroundColor = finalVal;
}
我只是简单地添加了哈希符号并以与输出值("#" + retVal
相同的方式附加它(,我将其添加到变量(finalVal
(中并输出它。