从一种颜色到另一种颜色的百分比

时间:2017-05-27 00:12:07

标签: javascript html css

在我的网站上我有一个变量,我们称之为x,它是一个百分比,我需要的是一种定义0%是红色而100%是蓝色的方法,所以如果我从x获得50%它们的颜色应该是这两种颜色的组合,如果我得到70%应该是红色强度更大的组合,依此类推任何百分比x给我。

1 个答案:

答案 0 :(得分:4)

红色有六位代码是:ff0000(十进制代码是:16711680),蓝色有0000ff(十进制代码是255)。您可以使用parseInt(hexcode,16)将十六进制转换为十进制。您的算法是:最大值16711680是100%;最小值255为0%。然后x%将是255+(16711680-255)* x / 100。并且您需要使用toString(16)将此值转换为十六进制。 这里的例子:

$('#control').change(function(e){
  var vl = $(this).val();
  var min = 255; //blue color -> 0000ff
  var max = 16711680; //red color -> ff0000
  var current = 255+Math.round(vl*(max-min)/100);
  var hex = current.toString(16);
  var currentHex = '#'+'0'.repeat(6-hex.length)+hex;
  $('#colorcode').html(currentHex);
  $('#box').css('backgroundColor', currentHex);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='range' value='0' min='0' max='100' id='control' style='width:200px;'>
<div id='colorcode'>Color code</div>
<div style='width:200px;height:200px;background-color:#0000ff;' id='box'></div>

相关问题