JS - 使用变量设置Div背景颜色 [英] JS - Setting Div background color using a variable
问题描述
基本上,我的一个同学练习JS,他有一个测试基本网站的想法。所以我说我们会有一场比赛来完成它。在这一点上,我们都遇到了一个错误。我们在JS中创建了一个颜色。但是当我们需要输出它不工作。我有这个。
Well basically, one of my mates was practicing JS and he had an idea of a test basic site. So I said we would have a race to complete it. We have both run in to an error at this point. We have created a color in JS. However when we need to output it does not work. I have this.
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 + ")\"";
将当前颜色放在中意味着它期望currentColor的值。不是实际的变数值。
Putting current color in "" would mean it's expecting the value of currentColor. Not the actual variable value.
希望有意义。这是可能的,还是我们在错误的树上?
Hope that makes sense. Is this possible, or are we barking up the wrong tree?
感谢
编辑:
#outputColor
{
height: 100px;
width: 100px;
background-color: rgb(0,0,0);
}
编辑:解决,解决方案是
Solved, solution is
currentColor = "rgb(" + part1 + ", " + part2 + ", " + part3 + ")";
谢谢大家!
推荐答案
有太多的双引号,请使用:
There are too much double-quotes, use this:
currentColor = "rgb (" + part1 + ", " + part2 + ", " + part3 + ")";
这篇关于JS - 使用变量设置Div背景颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!