admin管理员组

文章数量:1391995

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.

本文标签: javascriptJSSetting Div background color using a variableStack Overflow