Set background color to value of range input [closed]

你。 提交于 2019-12-14 03:35:36

问题


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


来源:https://stackoverflow.com/questions/15050671/set-background-color-to-value-of-range-input

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!