将数字转换为十六进制值,但使它们成为两位数

Turning numbers to hex values, but make them double digits

本文关键字:两位 十六进制 转换 数字      更新时间:2023-09-26

>问题:我正在构建一个使用数字到十六进制转换器功能的绘图板应用程序。目前,它们仅返回某些转换的个位数。

示例r:0,g:0, b:0返回 #000 ,而不是 #000000 。我相信这就是为什么我无法正确更新颜色的原因,只有值才能工作。

期望结果:我希望将我的数字转换为两位数。所以R:0,G:0,B:)会转换为#000000而不是#000,尽管它们是同一件事,但根据我的理解,其他颜色依赖于两位数。基本上,我希望我的所有数字到十六进制转换都是 6 位数字。

[已解决]:更改了将我的值获取到 css rgb(r,g,b)而不是使用十六进制值的方式。

捷斯宾 http://jsbin.com/doqiwocufa/edit?html,css,js,console,output

Javascript:

var $red = 0;
function changeRedNumboxValue(value) {
    var $numBox = $('#redNumber');
    $red = value;
    $numBox.val($red);
  
    console.log($red);
}
function changeRedSliderVal(value) {
    var $slider = $('#red');
    $red = value;
    $slider.val($red);
  
    console.log($red);
}
var $green = 0;
function changeGreenNumboxValue(value) {
    var $numBox = $('#greenNumber');
    $green = value;
    $numBox.val($green);
  
    console.log($green);
}
function changeGreenSliderVal(value) {
    var $slider = $('#green');
    $green = value;
    $slider.val($green);
  
    console.log($green);
}
var $blue = 0;
function changeBlueNumboxValue(value) {
    var $numBox = $('#blueNumber');
    $blue = value;
    $numBox.val($blue);
  
    console.log($blue);
}
function changeBlueSliderVal(value) {
    var $slider = $('#blue');
    $blue = value;
    $slider.val($blue);
  
    console.log($blue);
}
//CONVERT RGB TO HEX
function rgbToHex() {
    $hexRed = $red.toString(16);
    $hexGreen = $green.toString(16);
    $hexBlue = $blue.toString(16);
  
    console.log($hexRed);
    console.log($hexGreen);
    console.log($hexBlue);
  
    return '#' + $hexRed + $hexGreen + $hexBlue;
}
//UPDATE COLOR BASED ON HEX VALUES
function updateColor() {
    $colorChosen = $('#color-chosen');
    $color = rgbToHex();
    $colorChosen.css('background-color', $color);
}
updateColor();

.HTML:

<!DOCTYPE html>
<html>
   <head>
      <script src="https://code.jquery.com/jquery-2.1.4.js"></script>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width">
      <title>JS Bin</title>
   </head>
   <body>
      <span>Blue</span>
      <input id="red" type="range" name="amount2" value="0" min="0" max="255" oninput="changeNumboxValue(this.value)">
      <input id="redNumber" type="number" name="amountInput2" value="0" min="0" max="255" oninput="changeSliderVal(this.value)">
   </body>
</html>

.CSS:

#color-chosen {
    border: 1px solid black;
    width: 100px;
    height: 100px;
    margin: 0 auto;
}
你需要

一些用0填充并用String.prototype.slice()切割字符串:

slice() 方法提取字符串的一部分并返回一个新字符串。

 $hexRed = ('0' +  $red.toString(16)).slice(-2);

实际上,#ABC将被解释为#AABBCC。如果您只使用十六进制的 3 个数字,则它的颜色代码将是第一个字母的两倍、第二个字母的两倍和第三个字母的两倍。这意味着#000#000000相同。对于其他颜色,您可能需要r:AB 等。在这种情况下,gb需要用两个字母表示。

我认为这是你的问题。有时您会得到 1 个字母表示一种颜色,2 个字母表示其他颜色,从而导致 5 个六位数字转换。