Javascript颜色比例从0%到100%,可将其从任何颜色呈现为进度条上的任何颜色

时间:2018-11-13 13:41:07

标签: javascript progress-bar

我有一个进度条,我希望它可以将颜色从0%的红色渲染为100%的绿色。 我正在使用https://gist.github.com/mlocati/7210513处的js代码段,效果很好,但我想为0%和100%指定确切的颜色。

我想要的

红色:rgb(239, 83 ,80)为0%(#ef5350) 我想要的绿色:rgb( 54 ,161,14)表示100%(#36a10e)

我目前有红色:rgb(239, 0 ,80),(#ef0050) 我现在的绿色:rgb( 0 ,161,14)。 (#00a10e)

我如何获得83和54?

function perc2color() {

  var progressBar = $('#progress-bar');
  var value = $(progressBar).data('value');

  var r = 0;
  var g = 0;
  var b = 0;
  if (value < 50) {
    r = 239;
    g = Math.round(5.1 * value);
    b = 80;
  } else {
    r = Math.round(510 - 5.10 * value);
    g = 161;
    b = 14;
  }
  var h = r * 0x10000 + g * 0x100 + b * 0x1;
  window.alert('#' + ('000000' + h.toString(16)).slice(-6))
  progressBar.css({
    backgroundColor: '#' + ('000000' + h.toString(16)).slice(-6),
    width: value + '%'
  });
}
perc2color();
.progress-bar {
  height: 100%;
}

.progress {
  width: 100%;
  height: 25px;
  background-color: #eee;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="progress">
  <div class="progress-bar" id="progress-bar" data-value="100"></div>
</div>
<!-- to see the difference just change the number in data-value to anything between 0-100 -->

1 个答案:

答案 0 :(得分:0)

公式很简单:

 Math.round(start + (end - start) * value / 100);

这样,start将是0end将是100