javascript - 在 HTML 和 JavaScript 中使用两种颜色标度着色
问题描述
我有一个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. -->
是否有简洁的方法来执行此任务?
解决方案
const updateColor = (target) => {
const value = target.value;
//#00ff00 100
//#ffff00 50
//#ff0000 0
const R = Math.round((255 / 50) * (value < 50 ? 50 : 100 - value)).toString(16)
const G = Math.round((255 / 50) * (value > 50 ? 50 : value)).toString(16)
const twoDigit = (d) => ("0" + d).slice(-2);
const nextColor = '#' + twoDigit(R) + twoDigit(G) + '00';
target.style.background = nextColor
}
document.getElementById('color').addEventListener('change', (e) => updateColor(e.target));
document.addEventListener("DOMContentLoaded", function (event) {
updateColor(document.getElementById('color'))
});
<html>
<body>
<input type="number" id="color" min="0" max="100" value="0">
</body>
</html>
推荐阅读
- java - JavaFX 自定义控件主要方法
- vba - Word VBA 重复查找和替换与跟踪
- flutter - 在飞镖中做这两种等待未来的方法,返回相同的东西
- react-native - Unable to delete item from redux store, payload is a long list of strings
- json - Powershell 脚本无法正确解析
- android - 无法在 Xamarin.Android 上加载签名者
- docker - 赛普拉斯:容器无法启动。无法启动并监听 PORT 定义的端口
- python - 我不知道如何处理这种结构
- javascript - 在 aws lambda 中连接到 mongo 时出错
- android - 构建android应用程序cordova时JDK版本错误