首页 > 解决方案 > 在 HTML 和 JavaScript 中使用两种颜色标度着色

问题描述

我有一个input元素,其值为 0 到 100 之间的数字。我试图通过双色标度设置元素的样式,并将其值作为输入。

我打算做一个简单的渐变:

中间值应根据比例着色。

我曾尝试在 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. -->

是否有简洁的方法来执行此任务?

标签: javascripthtmlinputcolorslinear-gradients

解决方案


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>


推荐阅读