【问题标题】:How to get hex color value rather than RGB value?如何获得十六进制颜色值而不是 RGB 值?
【发布时间】:2010-12-16 23:26:18
【问题描述】:

使用以下 jQuery 将获取元素背景颜色的 RGB 值:

$('#selector').css('backgroundColor');

有没有办法获取十六进制值而不是 RGB?

【问题讨论】:

  • 在一个相关主题上,更多(并且可以说是更好的)在十六进制和 RGB 颜色之间转换的方法在这里:stackoverflow.com/questions/5623838/rgb-to-hex-and-hex-to-rgb 这个轮子已经被重新发明了足够多的时间来建造一辆公路列车。我希望流行的 JS 库之一,比 less 更简单,具有实用功能。
  • 请记住,有些浏览器返回 rgba(#,#,#,#),例如 rgba(0,0,0,0) 是透明的,而不是黑色的。第 4 个值是不透明度,1.0 为全彩 100%,0.5 为 50%。

标签: javascript jquery colors hex rgb


【解决方案1】:
var hexDigits = new Array
        ("0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"); 

//Function to convert rgb color to hex format
function rgb2hex(rgb) {
 rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
 return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]);
}

function hex(x) {
  return isNaN(x) ? "00" : hexDigits[(x - x % 16) / 16] + hexDigits[x % 16];
 }

(Source)

【讨论】:

  • +1,您可以使用 Number.toString(16) - 至少对于每个十六进制数字(如果小于 16,则用 0 填充)
  • -1。正如 orip 所提到的,您可以使用 toString(16)。因其他低效率而被否决。如果您要在每个函数调用中声明 hexDigits,至少在 rgb2hex 的函数体(而不是 hex 的体)中进行,因此每次调用 rgb2hex 时不会重新定义 3 次数组。还要学会使用'var',这样就不会污染全局范围。
  • 这种方法似乎不太能容忍不同的空格或大写字母。 jsfiddle.net/Xotic750/pSQ7d
  • 如果你真的想学究气,你可以让正则表达式更宽松:rgb.match(/^rgb\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)$/i) 但是,给出的正则表达式是为了应对浏览器在使用 jQuery 时给出的格式而设计的,这并没有'没有你正在谈论的不同的空白或captilisation一致性。您也可以使用相同的正则表达式,并在匹配 rgb 之前删除所有空格并转换为小写。附:您的小提琴示例:'rgb(10, 128,)' 我认为测试不合理
  • @SlimFadi 您的正则表达式不起作用,因为您未转义括号。修复后,它也会匹配 rgb(0, 0, 0, 0) 和 rgba(0, 0 ,0) 等无效值,但这不应该成为问题。
【解决方案2】:

TLDR

rgbrgba 支持下使用这个简洁的单行函数:

const rgba2hex = (rgba) => `#${rgba.match(/^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(\d+\.{0,1}\d*))?\)$/).slice(1).map((n, i) => (i === 3 ? Math.round(parseFloat(n) * 255) : parseFloat(n)).toString(16).padStart(2, '0').replace('NaN', '')).join('')}`

2021 年更新答案

自从我最初回答这个问题以来已经过去了很长时间。然后很酷的 ECMAScript 5 和 2015+ 功能在浏览器上大量可用,例如 arrow functionsArray.mapString.padStarttemplate strings。所以现在可以写一个单行rgb2hex

const rgb2hex = (rgb) => `#${rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/).slice(1).map(n => parseInt(n, 10).toString(16).padStart(2, '0')).join('')}`

// Use as you wish...
console.log(rgb2hex('rgb(0,0,0)'))
console.log(rgb2hex('rgb(255, 255, 255)'))
console.log(rgb2hex('rgb(255,0,0)'))
console.log(rgb2hex('rgb(38, 170, 90)'))

基本上,我们使用正则表达式来获取rgb字符串中的每个数字,slice(1)只获取数字(match的第一个结果是完整的字符串本身),map进行迭代每个数字,每次迭代都使用parseInt 转换为Number,然后返回十六进制String(通过base-16 转换),如果需要,通过padStart 添加零。最后,只需将join 每个转换/调整后的数字转换为唯一的String,以'#' 开头。

当然,我们可以毫不费力地将其扩展为单行代码rgba2hex

const rgba2hex = (rgba) => `#${rgba.match(/^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(\d+\.{0,1}\d*))?\)$/).slice(1).map((n, i) => (i === 3 ? Math.round(parseFloat(n) * 255) : parseFloat(n)).toString(16).padStart(2, '0').replace('NaN', '')).join('')}`

// Now it doesn't matter if 'rgb' or 'rgba'...
console.log(rgba2hex('rgb(0,0,0)'))
console.log(rgba2hex('rgb(255, 255, 255)'))
console.log(rgba2hex('rgb(255,0,0)'))
console.log(rgba2hex('rgb(38, 170, 90)'))
console.log(rgba2hex('rgba(255, 0, 0, 0.5)'))
console.log(rgba2hex('rgba(0,255,0,1)'))
console.log(rgba2hex('rgba(127,127,127,0.25)'))

就是这样。但是,如果您想深入了解旧式 JavaScript 世界,请继续阅读。


2010 年原始答案

这是我根据@Matt 建议编写的更清洁的解决方案:

function rgb2hex(rgb) {
    rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
    function hex(x) {
        return ("0" + parseInt(x).toString(16)).slice(-2);
    }
    return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]);
}

某些浏览器已经将颜色返回为十六进制(从 Internet Explorer 8 及更低版本开始)。如果您需要处理这些情况,只需在函数内附加一个条件,就像@gfrobenius 建议的那样:

function rgb2hex(rgb) {
    if (/^#[0-9A-F]{6}$/i.test(rgb)) return rgb;

    rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
    function hex(x) {
        return ("0" + parseInt(x).toString(16)).slice(-2);
    }
    return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]);
}

如果您使用 jQuery 并且想要更完整的方法,您可以使用自 jQuery 1.4.3 起可用的CSS Hooks,正如我在回答这个问题时所展示的那样:Can I force jQuery.css("backgroundColor") returns on hexadecimal format?

【讨论】:

  • 我建议大家:看看我的回复here,看看使用jQuery CSS Hooks的改进版本。
  • @Ghigo,对不起,你错了。 IE8 在获取当前样式时已经将颜色返回为十六进制,这样:document.getElementById("your_id").currentStyle["backgroundColor"]。不需要函数rgb2hex()。这是我上面建议的使用 CSS Hooks 的 jQuery 插件,它已经完成了所有验证以在不同的浏览器中恢复颜色:stackoverflow.com/questions/6177454/…
  • @Ghigo,我认为您误解了:如果您在以十六进制返回的浏览器中,则不应使用此功能。此函数将 RGB 转换为 HEX,仅此而已。当它不是 RGB 时不要使用它。您需要一个更完整的解决方案(它检测值是否已经是 RGB,正如@Jim-F 所做的那样)这一事实并没有改变这个解决方案提供的正是 OP 所要求的事实。抱歉,您的反对票毫无意义。
  • 对不起,我不同意。跨浏览器功能总是优于需要基于浏览器检测执行的功能。 Op 要求将 $('#selector').css('backgroundColor') 转换为十六进制,而不是将 rgb 值转换为十六进制。而在 IE8 上,$('#selector').css('backgroundColor') 已经是十六进制,因此必须对其进行处理。而已。不要生我的气:)
  • 做这件事,我添加到rgb2hex() 函数中的一个简单的衬里,谢谢@ErickPetru!不管你信不信,我必须将代码重新编码回 IE7。使用.css('backgroundColor') 和本机obj.style.backgroundColor IE7 & 8 将返回十六进制,而不是 RGB,所以我在提供的答案中将其添加为rgb2hex() 函数的第一行,因此它可以一直返回到 IE7:/* IE7&8 will return hex, so no need to run this function if it is already hex. */ if (/^#[0-9A-F]{6}$/i.test(rgb)) return rgb.substring(1, 7); //I'm doing a subtring here because I do not want the leading # symbol希望有帮助。
【解决方案3】:

更新了@ErickPetru 以实现 rgba 兼容性:

function rgb2hex(rgb) {
    rgb = rgb.match(/^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(\d+))?\)$/);
    function hex(x) {
        return ("0" + parseInt(x).toString(16)).slice(-2);
    }
    return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]);
}

我更新了正则表达式以匹配 alpha 值(如果已定义),但不使用它。

【讨论】:

  • 只是为了完整性:我正在做一个将导出到 PowerPoint 的东西(不要问...),它接受 alpha 通道的十六进制字符串上的第四个字节,所以一个可以像这样使用它:return hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]) /* Add the alpha channel if it exists */ + (rgb[5] !== undefined ? hex(Math.round(rgb[5] * 255)) : ''); 另外,我正在删除# 符号以使其与最终用途无关(例如,可以获取输出并在其前面加上0x,或者不带前缀) .希望它可以帮助别人!
【解决方案4】:

大多数浏览器在使用时似乎会返回 RGB 值:

$('#selector').css('backgroundColor');

只有 I.E(目前只测试了 6 个)返回十六进制值。

为避免在 IE 中出现错误消息,您可以将函数包装在 if 语句中:

function rgb2hex(rgb) {
     if (  rgb.search("rgb") == -1 ) {
          return rgb;
     } else {
          rgb = rgb.match(/^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(\d+))?\)$/);
          function hex(x) {
               return ("0" + parseInt(x).toString(16)).slice(-2);
          }
          return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]); 
     }
}

【讨论】:

  • 这个比大多数其他的效果更好,因为 Jim 考虑了 rgba,这是 Safari(至少在 Mac OS X 上)使用的。谢谢,吉姆!
  • 很好的解决方案。请注意,函数返回小写字母,即 #ff5544 而不是 #FF5544。
  • 这个正则表达式在上述解决方案中也将支持 aplha 通道 rgb = rgb.match(/^rgba?((\d+),\s*(\d+),\s*(\d+ )(?:,\s*(0\.\d+))?)$/);
【解决方案5】:

这是我发现的一个不会在 IE 中引发脚本错误的解决方案: http://haacked.com/archive/2009/12/29/convert-rgb-to-hex.aspx

【讨论】:

  • 在旧版本的 IE 中,使用 jquery 获取对象的颜色值有时会返回 hex 而不是 rgb,而大多数现代浏览器返回 RGB。链接到函数处理这两个用例
【解决方案6】:

这是一个也检查透明的版本,我需要这个,因为我的对象是将结果插入到样式属性中,其中十六进制颜色的透明版本实际上是单词“透明”..

function rgb2hex(rgb) {
     if (  rgb.search("rgb") == -1 ) {
          return rgb;
     }
     else if ( rgb == 'rgba(0, 0, 0, 0)' ) {
         return 'transparent';
     }
     else {
          rgb = rgb.match(/^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(\d+))?\)$/);
          function hex(x) {
               return ("0" + parseInt(x).toString(16)).slice(-2);
          }
          return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]); 
     }
}

【讨论】:

    【解决方案7】:

    这是我的解决方案,touppercase 也通过使用参数来检查提供的字符串中是否存在其他可能的空格和大写。

    var a = "rgb(10, 128, 255)";
    var b = "rgb( 10, 128, 255)";
    var c = "rgb(10, 128, 255 )";
    var d = "rgb ( 10, 128, 255 )";
    var e = "RGB ( 10, 128, 255 )";
    var f = "rgb(10,128,255)";
    var g = "rgb(10, 128,)";
    
    var rgbToHex = (function () {
        var rx = /^rgb\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)$/i;
    
        function pad(num) {
            if (num.length === 1) {
                num = "0" + num;
            }
    
            return num;
        }
    
        return function (rgb, uppercase) {
            var rxArray = rgb.match(rx),
                hex;
    
            if (rxArray !== null) {
                hex = pad(parseInt(rxArray[1], 10).toString(16)) + pad(parseInt(rxArray[2], 10).toString(16)) + pad(parseInt(rxArray[3], 10).toString(16));
    
                if (uppercase === true) {
                    hex = hex.toUpperCase();
                }
    
                return hex;
            }
    
            return;
        };
    }());
    
    console.log(rgbToHex(a));
    console.log(rgbToHex(b, true));
    console.log(rgbToHex(c));
    console.log(rgbToHex(d));
    console.log(rgbToHex(e));
    console.log(rgbToHex(f));
    console.log(rgbToHex(g));
    

    开启jsfiddle

    jsperf上的速度比较

    进一步的改进可能是trim() rgb 字符串

    var rxArray = rgb.trim().match(rx),
    

    【讨论】:

      【解决方案8】:

      颜色类取自引导颜色选择器

      // Color object
      var Color = function(val) {
          this.value = {
              h: 1,
              s: 1,
              b: 1,
              a: 1
          };
          this.setColor(val);
      };
      
      Color.prototype = {
          constructor: Color,
      
          //parse a string to HSB
          setColor: function(val){
              val = val.toLowerCase();
              var that = this;
              $.each( CPGlobal.stringParsers, function( i, parser ) {
                  var match = parser.re.exec( val ),
                  values = match && parser.parse( match ),
                  space = parser.space||'rgba';
                  if ( values ) {
                      if (space === 'hsla') {
                          that.value = CPGlobal.RGBtoHSB.apply(null, CPGlobal.HSLtoRGB.apply(null, values));
                      } else {
                          that.value = CPGlobal.RGBtoHSB.apply(null, values);
                      }
                      return false;
                  }
              });
          },
      
          setHue: function(h) {
              this.value.h = 1- h;
          },
      
          setSaturation: function(s) {
              this.value.s = s;
          },
      
          setLightness: function(b) {
              this.value.b = 1- b;
          },
      
          setAlpha: function(a) {
              this.value.a = parseInt((1 - a)*100, 10)/100;
          },
      
          // HSBtoRGB from RaphaelJS
          // https://github.com/DmitryBaranovskiy/raphael/
          toRGB: function(h, s, b, a) {
              if (!h) {
                  h = this.value.h;
                  s = this.value.s;
                  b = this.value.b;
              }
              h *= 360;
              var R, G, B, X, C;
              h = (h % 360) / 60;
              C = b * s;
              X = C * (1 - Math.abs(h % 2 - 1));
              R = G = B = b - C;
      
              h = ~~h;
              R += [C, X, 0, 0, X, C][h];
              G += [X, C, C, X, 0, 0][h];
              B += [0, 0, X, C, C, X][h];
              return {
                  r: Math.round(R*255),
                  g: Math.round(G*255),
                  b: Math.round(B*255),
                  a: a||this.value.a
              };
          },
      
          toHex: function(h, s, b, a){
              var rgb = this.toRGB(h, s, b, a);
              return '#'+((1 << 24) | (parseInt(rgb.r) << 16) | (parseInt(rgb.g) << 8) | parseInt(rgb.b)).toString(16).substr(1);
          },
      
          toHSL: function(h, s, b, a){
              if (!h) {
                  h = this.value.h;
                  s = this.value.s;
                  b = this.value.b;
              }
              var H = h,
              L = (2 - s) * b,
              S = s * b;
              if (L > 0 && L <= 1) {
                  S /= L;
              } else {
                  S /= 2 - L;
              }
              L /= 2;
              if (S > 1) {
                  S = 1;
              }
              return {
                  h: H,
                  s: S,
                  l: L,
                  a: a||this.value.a
              };
          }
      };
      

      如何使用

      var color = new Color("RGB(0,5,5)");
      color.toHex()
      

      【讨论】:

        【解决方案9】:

        这个好看一点:

        var rgb = $('#selector').css('backgroundColor').match(/\d+/g);
        var r   = parseInt(rgb[0], 10);
        var g   = parseInt(rgb[1], 10);
        var b   = parseInt(rgb[2], 10);
        var hex = '#'+ r.toString(16) + g.toString(16) + b.toString(16);
        

        更简洁的单行:

        var rgb = $('#selector').css('backgroundColor').match(/\d+/g);
        var hex = '#'+ Number(rgb[0]).toString(16) + Number(rgb[1]).toString(16) + Number(rgb[2]).toString(16);
        

        强制 jQuery 总是返回十六进制:

        $.cssHooks.backgroundColor = {
            get: function(elem) {
                if (elem.currentStyle)
                    var bg = elem.currentStyle["backgroundColor"];
                else if (window.getComputedStyle) {
                    var bg = document.defaultView.getComputedStyle(elem,
                        null).getPropertyValue("background-color");
                }
                if (bg.search("rgb") == -1) {
                    return bg;
                } else {
                    bg = bg.match(/\d+/g);
                    function hex(x) {
                        return ("0" + parseInt(x).toString(16)).slice(-2);
                    }
                    return "#" + hex(bg[0]) + hex(bg[1]) + hex(bg[2]);
                }
            }
        }
        

        【讨论】:

          【解决方案10】:

          Steven Pribilinskiy 的答案去掉了前导零,例如 #ff0000 变为 #ff00。

          一种解决方案是在最后 2 位数字后面附加一个前导 0 和子字符串。

          var rgb = $('#selector').css('backgroundColor').match(/\d+/g);
          var hex = '#'+ String('0' + Number(rgb[0]).toString(16)).slice(-2) + String('0' + Number(rgb[1]).toString(16)).slice(-2) + String('0' + Number(rgb[2]).toString(16)).slice(-2);
          

          【讨论】:

            【解决方案11】:

            以十六进制返回元素背景颜色的函数。

            function getBgColorHex(elem){
                var color = elem.css('background-color')
                var hex;
                if(color.indexOf('#')>-1){
                    //for IE
                    hex = color;
                } else {
                    var rgb = color.match(/\d+/g);
                    hex = '#'+ ('0' + parseInt(rgb[0], 10).toString(16)).slice(-2) + ('0' + parseInt(rgb[1], 10).toString(16)).slice(-2) + ('0' + parseInt(rgb[2], 10).toString(16)).slice(-2);
                }
                return hex;
            }
            

            用法示例:

            $('#div1').click(function(){
               alert(getBgColorHex($(this));
            }
            

            jsfiddle

            【讨论】:

              【解决方案12】:

              可读 && 免费 Reg-exp(无 Reg-exp)

              我创建了一个使用可读基本函数且没有正则表达式的函数。
              该函数接受十六进制、rgb 或rgba CSS格式的颜色并返回十六进制表示。
              编辑:解析 rgba() 格式时存在错误,已修复...

              function getHexColor( color ){
                  //if color is already in hex, just return it...
                  if( color.indexOf('#') != -1 ) return color;
                  
                  //leave only "R,G,B" :
                  color = color
                              .replace("rgba", "") //must go BEFORE rgb replace
                              .replace("rgb", "")
                              .replace("(", "")
                              .replace(")", "");
                  color = color.split(","); // get Array["R","G","B"]
                  
                  // 0) add leading #
                  // 1) add leading zero, so we get 0XY or 0X
                  // 2) append leading zero with parsed out int value of R/G/B
                  //    converted to HEX string representation
                  // 3) slice out 2 last chars (get last 2 chars) => 
                  //    => we get XY from 0XY and 0X stays the same
                  return  "#"
                          + ( '0' + parseInt(color[0], 10).toString(16) ).slice(-2)
                          + ( '0' + parseInt(color[1], 10).toString(16) ).slice(-2)
                          + ( '0' + parseInt(color[2], 10).toString(16) ).slice(-2);
              }
              

              【讨论】:

              • 不适用于 rgba(0,0,0,0)。首先:订单需要更改.replace("rgba", "") .replace("rgb", "") .replace("(", "") .replace(")", ""); 否则,您将得到a0,0,0,0。并且,它返回#000000,即黑色,而不是透明。
              • 如果 rgba 中的第 4 个值是 0(零),那么对于该“元素”的 css 将是: element{ color: #000000, opacity: 0.0;} 这是透明的或只是有条件的将 'rgba(0,0,0,0)' 返回给调用者。
              • @Twelve24 解析已修复 - 在阅读您的评论之前,我实际上注意到了这一点,但绝对感谢 :),至于透明度 - 函数应该返回 HEXA 颜色,或者“基色” - 所以一个是故意 :)
              【解决方案13】:

              这是一个不使用 jQuery 的 ES6 one liner:

              var rgb = document.querySelector('#selector').style['background-color'];
              return '#' + rgb.substr(4, rgb.indexOf(')') - 4).split(',').map((color) => parseInt(color).toString(16).padStart(2, '0')).join('');
              

              【讨论】:

              • 谢谢,这帮助我将它合并到一个 Wordpress 页面中,该页面去除了之前答案中的正则表达式反斜杠。
              • 此答案不适用于小数字,例如parseInt('0').toString(16) # =&gt; '0',如果是单个数字则必须填充字符串parseInt('0').toString(16).padStart(2, '0') =&gt; '00'
              【解决方案14】:

              同样的答案 like @Jim F answerES6 语法,所以,更少的指令:

              const rgb2hex = (rgb) => {
                if (rgb.search("rgb") === -1) return rgb;
                rgb = rgb.match(/^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(\d+))?\)$/);
                const hex = (x) => ("0" + parseInt(x).toString(16)).slice(-2);
                return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]);
              };
              

              【讨论】:

                【解决方案15】:

                只是为了添加到上面@Justin 的答案..

                应该是

                var rgb = document.querySelector('#selector').style['background-color'];
                return '#' + rgb.substr(4, rgb.indexOf(')') - 4).split(',').map((color) => String("0" + parseInt(color).toString(16)).slice(-2)).join('');
                

                由于上述解析 int 函数会截断前导零,因此产生 5 或 4 个字母的不正确颜色代码可能是......即对于 rgb(216,160,10),它产生 #d8a0a 而它应该是 #d8a00a。

                谢谢

                【讨论】:

                  【解决方案16】:

                  由于问题是使用 JQuery,这里有一个基于 Daniel Elliott 代码的 JQuery 插件:

                  $.fn.cssAsHex = function(colorProp) {
                  
                      var hexDigits = '0123456789abcdef';
                  
                      function hex(x) {
                          return isNaN(x) ? '00' : hexDigits[(x - x % 16) / 16] + hexDigits[x % 16];
                      };
                  
                      // Convert RGB color to Hex format
                      function rgb2hex(rgb) {
                          var rgbRegex = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
                          return '#' + hex(rgbRegex[1]) + hex(rgbRegex[2]) + hex(rgbRegex[3]);
                      };
                  
                      return rgb2hex(this.css(colorProp));
                  };
                  

                  像这样使用它:

                  var hexBackgroundColor = $('#myElement').cssAsHex('background-color');
                  

                  【讨论】:

                    【解决方案17】:

                    我美丽的非标解决方案

                    HTML

                    <div id="selector" style="background-color:#f5b405"></div>
                    

                    jQuery

                    $("#selector").attr("style").replace("background-color:", "");
                    

                    结果

                    #f5b405
                    

                    【讨论】:

                    • 它返回样式中的所有内容。 :c
                    【解决方案18】:

                    试试

                    // c - color str e.g."rgb(12,233,43)", result color hex e.g. "#0ce92b"
                    let rgb2hex= c=> '#'+c.match(/\d+/g).map(x=>(+x).toString(16).padStart(2,0)).join``
                    

                    // rgb - color str e.g."rgb(12,233,43)", result color hex e.g. "#0ce92b"
                    let rgb2hex= c=> '#'+c.match(/\d+/g).map(x=>(+x).toString(16).padStart(2,0)).join``
                    
                    console.log(rgb2hex("rgb(12,233,43"));

                    【讨论】:

                      【解决方案19】:

                      Convert RGB to Hex

                      我正在使用 Jasmine 量角器,但出现了类似的错误 - Expected [ 'rgba(255, 255, 255, 1)' ] to contain '#fff'. 下面的功能对我来说很好。

                      function RGBAToHexA(test:string) {
                      let sep = test.toString().indexOf(",") > -1 ? "," : " ";
                      const rgba = test.toString().substring(5).split(")")[0].split(sep);
                      console.log(rgba)
                      let r = (+rgba[0]).toString(16),
                        g = (+rgba[1]).toString(16),
                        b = (+rgba[2]).toString(16),
                        a = Math.round(+rgba[3] * 255).toString(16);
                      
                          if (r.length == 1)
                              r = "0" + r;
                          if (g.length == 1)
                              g = "0" + g;
                          if (b.length == 1)
                              b = "0" + b;
                          if (a.length == 1)
                              a = "0" + a;
                      
                      return "#" + r + g + b + a;
                      

                      }

                      describe('Check CSS', function() {
                       
                      it('should check css of login page', async function(){
                              browser.waitForAngularEnabled(true);
                              browser.actions().mouseMove(element(by.css('.btn-auth, .btn-auth:hover'))).perform(); // mouse hover on button
                              csspage.Loc_auth_btn.getCssValue('color').then(function(color){
                                  console.log(RGBAToHexA(color))
                                  expect( RGBAToHexA(color)).toContain(cssData.hoverauth.color);
                      
                              })
                      
                             
                      

                      【讨论】:

                      • 您可以将if (r.length == 1) ... r = "0" + r; 替换为*.padStart(2, "0")
                      【解决方案20】:

                      对于所有函数式编程爱好者,这里有一个有点函数式的方法:)

                      const getHexColor = (rgbValue) =>
                        rgbValue.replace("rgb(", "").replace(")", "").split(",")
                          .map(colorValue => (colorValue > 15 ? "0" : "") + colorValue.toString(16))
                          .reduce((acc, hexValue) => acc + hexValue, "#")
                      

                      然后像这样使用它:

                      const testRGB = "rgb(13,23,12)"
                      getHexColor(testRGB)
                      

                      【讨论】:

                        【解决方案21】:

                        我的精简版

                        //Function to convert rgb color to hex format
                        function rgb2hex(rgb) {
                            if(/^#/.test(rgb))return rgb;// if returns colors as hexadecimal
                            let re = /\d+/g;
                            let hex = x => (x >> 4).toString(16)+(x & 0xf).toString(16);
                            return "#"+hex(re.exec(rgb))+hex(re.exec(rgb))+hex(re.exec(rgb));
                        }

                        【讨论】:

                          【解决方案22】:

                          改进的函数“十六进制”

                          function hex(x){
                              return isNaN(x) ? "00" : hexDigits[x >> 4] + hexDigits[x & 0xf];
                              // or option without hexDigits array
                              return (x >> 4).toString(16)+(x & 0xf).toString(16);
                          }
                          

                          【讨论】:

                            【解决方案23】:

                            完整案例(rgb、rgba、透明...等)解决方案(coffeeScript)

                             rgb2hex: (rgb, transparentDefault=null)->
                                return null unless rgb
                                return rgb if rgb.indexOf('#') != -1
                                return transparentDefault || 'transparent' if rgb == 'rgba(0, 0, 0, 0)'
                                rgb = rgb.match(/^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(\d+))?\)$/);
                                hex = (x)->
                                  ("0" + parseInt(x).toString(16)).slice(-2)
                            
                                '#' + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3])
                            

                            【讨论】:

                              猜你喜欢
                              • 1970-01-01
                              • 1970-01-01
                              • 2021-02-17
                              • 1970-01-01
                              • 2018-10-22
                              相关资源
                              最近更新 更多