将背景颜色设置为范围输入的值

时间:2013-02-24 10:09:53

标签: javascript colors range background-color rgb

这是我的代码:

<input id="red" name="red" type="range" min="0" max="255" step="1" value="128></input>
<label for="red">red</label>
<br>
<input id="green" name="green" type="range" min="0" max="255" step="1" value="128"></input>
<label for="green">green</label>
<br>
<input id="blue" name="blue" type="range" min="0" max="255" step="1" value="128"></input>
<label for="blue">blue</label> 

如何使用JavaScript根据范围(RGB)的值设置背景颜色(html正文)?

1 个答案:

答案 0 :(得分:0)

您要做的是在输入中添加一个onchange部分,以便在用户更改输入滑块的值时进行处理。这就是它的样子:

<input id="red" name="red" type="range" min="0" max="255" step="1" value="128" onchange="changeColor()"></input>
<label for="red">red</label>
<br>
<input id="green" name="green" type="range" min="0" max="255" step="1" value="128" onchange="changeColor()"></input>
<label for="green">green</label>
<br>
<input id="blue" name="blue" type="range" min="0" max="255" step="1" value="128" onchange="changeColor()"></input>
<label for="blue">blue</label>

现在你想创建一个实际改变背景颜色的函数:

function changeColor(){
    var red = document.getElementById("red").value;
    var green = document.getElementById("green").value;
    var blue = document.getElementById("blue").value;
    document.body.style.background = "rgb(" + red + "," + green + "," + blue + ")";
}