最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - JS - Setting Div background color using a variable - Stack Overflow

programmeradmin1浏览0评论

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 plete 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;

Where current color is made via this

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 + ")\"";

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?

Thanks

Edit: It does have a css style assosiated with it already

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

Edit: Solved, solution is

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

Thank you all!

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 plete 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;

Where current color is made via this

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 + ")\"";

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?

Thanks

Edit: It does have a css style assosiated with it already

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

Edit: Solved, solution is

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

Thank you all!

Share Improve this question edited Jun 16, 2012 at 22:42 Kyle93 asked Jun 16, 2012 at 22:23 Kyle93Kyle93 7955 gold badges16 silver badges27 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 4

There are too much double-quotes, use this:

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

OR Using Hex format

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

DEMO.

发布评论

评论列表(0)

  1. 暂无评论