<div> <label for="red">Red:</label> <input type="range" min="0" max="255" id="red"> </div> <div> <label for="green">Green:</label> <input type="range" min="0" max="255" id="green"> </div> <div> <label for="blue">Blue:</label> <input type="range" min="0" max="255" id="blue"> </div> <div> <h2>Current color:</h2> <div id="color"></div> </div> <script> const red = document.getElementById('red'); const green = document.getElementById('green'); const blue = document.getElementById('blue'); const color = document.getElementById('color'); function updateColor() { const r = red.value; const g = green.value; const b = blue.value; color.style.backgroundColor = `rgb(${r}, ${g}, ${b})`; color.innerHTML = `RGB: ${r}, ${g}, ${b}`; } red.addEventListener('input', updateColor); green.addEventListener('input', updateColor); blue.addEventListener('input', updateColor); </script> 除了滚动条设置背景色,还可以在输入框输入三个rgb的值实现背景色的更改
时间: 2024-02-03 15:12:47 浏览: 115
是的,你可以通过在输入框中输入三个RGB值来实现背景色的更改。可以使用以下代码来实现:
```html
<div>
<label for="red">Red:</label>
<input type="number" min="0" max="255" id="red">
</div>
<div>
<label for="green">Green:</label>
<input type="number" min="0" max="255" id="green">
</div>
<div>
<label for="blue">Blue:</label>
<input type="number" min="0" max="255" id="blue">
</div>
<div>
<h2>Current color:</h2>
<div id="color"></div>
</div>
<script>
const red = document.getElementById('red');
const green = document.getElementById('green');
const blue = document.getElementById('blue');
const color = document.getElementById('color');
function updateColor() {
const r = red.value;
const g = green.value;
const b = blue.value;
color.style.backgroundColor = `rgb(${r}, ${g}, ${b})`;
color.innerHTML = `RGB: ${r}, ${g}, ${b}`;
}
red.addEventListener('input', updateColor);
green.addEventListener('input', updateColor);
blue.addEventListener('input', updateColor);
// listen for changes in the input fields
red.addEventListener('change', updateColor);
green.addEventListener('change', updateColor);
blue.addEventListener('change', updateColor);
</script>
```
这里我们添加了三个输入框,类型为 `number`,用于输入RGB的值。然后,我们在 `updateColor()` 函数中读取这些值并设置为背景色。最后,我们添加了 `change` 事件监听器,以便在输入框中输入值时也可以更新颜色。
阅读全文