JS - 使用变量设置 Div 背景颜色

JS - Setting Div background color using a variable

本文关键字:Div 背景 颜色 设置 变量 JS      更新时间:2023-09-26

基本上,我的一个伙伴正在练习JS,他有一个测试基本站点的想法。所以我说我们会有一场比赛来完成它。在这一点上,我们都遇到了错误。我们在 JS 中创建了一个颜色。但是,当我们需要输出时,它不起作用。我有这个。

document.getElementById("outputColor").style.backgroundColor=currentColor;

通过此制作当前颜色的地方

part1 = Math.floor(Math.random() * (255 - 0 + 1)) + 0;
part2 = Math.floor(Math.random() * (255 - 0 + 1)) + 0;
part3 = Math.floor(Math.random() * (255 - 0 + 1)) + 0;
currentColor = "'"rgb (" + part1 + ", " + part2 + ", " + part3 + ")'"";
将当前颜色

放在"中意味着它期望当前颜色的值。不是实际的变量值。

希望这是有道理的。这是可能的,还是我们吠错了树?

谢谢

编辑:它确实已经有一个与之关联的 css 样式

#outputColor
{
    height: 100px;
    width: 100px;
    background-color: rgb(0,0,0);
}

编辑:已解决,解决方案是

currentColor = "rgb(" + part1 + ", " + part2 + ", " + part3 + ")";

谢谢大家!

双引号太多,请使用这个:

currentColor = "rgb(" + part1 + ", " + part2 + ", " + part3 + ")";
currentColor = "rgba(" + part1 + ", " + part2 + ", " + part3 + ",0)";
currentColor = "rgb(" + part1 + ", " + part2 + ", " + part3 + ")"; // RGB

或使用十六进制格式

currentColorHex="#"+(part1).toString(16)+(part2).toString(16)+(part3).toString(16);

演示。