Set background color to value of range input [clos

2019-09-24 10:46发布

问题:

This is my code:

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

How can I set the background color (of html body) according to the values of the ranges (RGB) using JavaScript?

回答1:

What you want to do is add an onchange part to your inputs to handle when the user changes the values of your input sliders. This is what it would look like:

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

Now you want to make a function that will actually change the background color:

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