from green to red color depend on percentage

前端 未结 14 2062
北恋
北恋 2020-11-30 20:00

I have a poll system and I want answers for this poll to be colored. For example: If it\'s 10% it would be red, if 40% it would be yellow and if 80% it would be green, so I

14条回答
  •  囚心锁ツ
    2020-11-30 20:38

    A simple scheme using HSL along with fiddle:

    function getColor(value){
        //value from 0 to 1
        var hue=((1-value)*120).toString(10);
        return ["hsl(",hue,",100%,50%)"].join("");
    }
    

    tweak saturation and luminosity as needed. and a fiddle.

    function getColor(value) {
      //value from 0 to 1
      var hue = ((1 - value) * 120).toString(10);
      return ["hsl(", hue, ",100%,50%)"].join("");
    }
    var len = 20;
    for (var i = 0; i <= len; i++) {
      var value = i / len;
      var d = document.createElement('div');
      d.textContent = "value=" + value;
      d.style.backgroundColor = getColor(value);
      document.body.appendChild(d);
    }

提交回复
热议问题