【发布时间】:2020-09-16 02:07:20
【问题描述】:
我有一个 input 元素,它的值是介于 0 和 100 之间的数字。我正在尝试通过双色标度设置元素的样式,并将其值作为输入。
我打算做一个简单的渐变:
- 当数字为100时,元素的背景色为绿色
#00ff00 - 数字为0时为红色
#ff0000 - 数字为50时显示黄色
#ffff00
中间值应根据比例着色。
我曾尝试在 JavaScript 中使用 if 语句,但未能创建渐变,因为红色、黄色和绿色之间存在硬边界(无渐变)。请看下面的代码:
var x = 0;
function color() {
x = document.getElementById("color").value;
console.log(x);
if (x > 50) {
document.getElementById('color').style.backgroundColor = "#00ff00";
}
else if (x == 50) {
document.getElementById('color').style.backgroundColor = "#ffff00";
}
else {
document.getElementById('color').style.backgroundColor = "#ff0000";
}
}
<button onclick="color();">Run</button>
<input type="number" id='color' value=50></input>
<!-- The input is not disabled for value debugging. -->
有没有简洁的方法来执行这个任务?
【问题讨论】:
-
由于 SO 不是代码编写服务,您应该发布您编写的代码以尝试解决此问题。
-
我刚刚做了,虽然我很困惑如何处理代码
标签: javascript html input colors linear-gradients