简体   繁体   English

将十六进制转换为 RGBA

[英]Convert Hex to RGBA

My fiddle - http://jsbin.com/pitu/1/edit我的小提琴 - http://jsbin.com/pitu/1/edit

I wanted to try an easy hex to rgba conversion.我想尝试一个简单的十六进制到 rgba 转换。 Ever browser I've used renders colors using rgb as default so when using the farbtastic color picker I'm converting the hex value to rgb by grabbing the background color the hex value generates (as rgb by default = simple conversion)我使用过的任何浏览器都会使用 rgb 作为默认值渲染 colors,因此当使用 farbtastic 颜色选择器时,我通过抓取十六进制值生成的背景颜色将十六进制值转换为 rgb(默认情况下为 rgb = 简单转换)

I tried replacing the ) symbol to , 1) , but that didn't work so I went to just see how converting rgb to rgba would work, and I'm still having trouble.我尝试将)符号替换为, 1) ,但这不起作用,所以我去看看将 rgb 转换为 rgba 是如何工作的,但我仍然遇到问题。

The jquery jquery

$('.torgb').val($('#color').css('background-color'));
$('.torgba').val().replace(/rgb/g,"rgba");

The goal目标
在此处输入图像描述

EDIT :编辑

TinyColor Is a great color manipulation js library that does everything I want here and more. TinyColor是一个很棒的颜色处理 js 库,可以在这里完成我想要的一切以及更多。 I figure you guys may want to give it a try!我想你们可能想试一试! - https://github.com/bgrins/TinyColor - https://github.com/bgrins/TinyColor

//If you write your own code, remember hex color shortcuts (eg., #fff, #000)

function hexToRgbA(hex){
    var c;
    if(/^#([A-Fa-f0-9]{3}){1,2}$/.test(hex)){
        c= hex.substring(1).split('');
        if(c.length== 3){
            c= [c[0], c[0], c[1], c[1], c[2], c[2]];
        }
        c= '0x'+c.join('');
        return 'rgba('+[(c>>16)&255, (c>>8)&255, c&255].join(',')+',1)';
    }
    throw new Error('Bad Hex');
}

hexToRgbA('#fbafff')

/*  returned value: (String)
rgba(251,175,255,1)
*/

@ElDoRado1239 has the right idea, but there's also a cleaner way: @ElDoRado1239 有正确的想法,但还有一种更清洁的方法:

 function hexToRGB(hex, alpha) { var r = parseInt(hex.slice(1, 3), 16), g = parseInt(hex.slice(3, 5), 16), b = parseInt(hex.slice(5, 7), 16); if (alpha) { return "rgba(" + r + ", " + g + ", " + b + ", " + alpha + ")"; } else { return "rgb(" + r + ", " + g + ", " + b + ")"; } } hexToRGB('#FF0000', 0.5);

ES6 function for only handling 6 character hex with or without the '#': ES6 函数仅处理带或不带'#'的 6 个字符的十六进制:

const hex2rgba = (hex, alpha = 1) => {
  const [r, g, b] = hex.match(/\w\w/g).map(x => parseInt(x, 16));
  return `rgba(${r},${g},${b},${alpha})`;
};

Usage:用法:

hex2rgba('#af087b', .5)   // returns: rgba(175,8,123,0.5)
hex2rgba('af087b', .5)    // returns: rgba(175,8,123,0.5)
hex2rgba('af087b')        // returns: rgba(175,8,123,1)

Clean TypeScript version:干净的 TypeScript 版本:

hexToRGB(hex: string, alpha: string) {

  const r = parseInt(hex.slice(1, 3), 16);
  const g = parseInt(hex.slice(3, 5), 16);
  const b = parseInt(hex.slice(5, 7), 16);

  if (alpha) {
    return `rgba(${r}, ${g}, ${b}, ${alpha})`;
  }

  return `rgb(${r}, ${g}, ${b})`;
}

Based on @AJFarkas's answer.基于@AJFarkas 的回答。

Any Hex Form Modular Approach任何十六进制形式的模块化方法

The main challenge is that as of 2018 there are a few forms of HEX.主要挑战是截至 2018 年有几种形式的 HEX。 The 6 char traditional form, the 3 char shorten form, and a new 4 and 8 char form that includes alpha. 6 个字符的传统形式、3 个字符的缩短形式以及包括 alpha 的新的 4 和 8 个字符的形式。 The following function can handle any HEX form.以下函数可以处理任何 HEX 形式。

const isValidHex = (hex) => /^#([A-Fa-f0-9]{3,4}){1,2}$/.test(hex)

const getChunksFromString = (st, chunkSize) => st.match(new RegExp(`.{${chunkSize}}`, "g"))

const convertHexUnitTo256 = (hexStr) => parseInt(hexStr.repeat(2 / hexStr.length), 16)

const getAlphafloat = (a, alpha) => {
    if (typeof a !== "undefined") {return a / 255}
    if ((typeof alpha != "number") || alpha <0 || alpha >1){
      return 1
    }
    return alpha
}

export const hexToRGBA = (hex, alpha) => {
    if (!isValidHex(hex)) {throw new Error("Invalid HEX")}
    const chunkSize = Math.floor((hex.length - 1) / 3)
    const hexArr = getChunksFromString(hex.slice(1), chunkSize)
    const [r, g, b, a] = hexArr.map(convertHexUnitTo256)
    return `rgba(${r}, ${g}, ${b}, ${getAlphafloat(a, alpha)})`
}

Alpha could be provided to the function in the following ways: Alpha 可以通过以下方式提供给函数:

  1. As part of a 4, or 8 form HEX .作为 4 或 8 形式 HEX 的一部分。
  2. As a second parameter between 0-1,作为0-1之间的第二个参数,

OutPut输出

    const c1 = "#f80"
    const c2 = "#f808"
    const c3 = "#0088ff"
    const c4 = "#0088ff88"
    const c5 = "#98736"

    console.log(hexToRGBA(c1))   //  rgba(255, 136, 0, 1)
    console.log(hexToRGBA(c2))   //  rgba(255, 136, 0, 0.53125)
    console.log(hexToRGBA(c3))   //  rgba(0, 136, 255, 1)
    console.log(hexToRGBA(c4))   //  rgba(0, 136, 255, 0.53125)
    console.log(hexToRGBA(c5))   //  Uncaught Error: Invalid HEX

    console.log(hexToRGBA(c1, 0.5))   //  rgba(255, 136, 0, 0.5)
    console.log(hexToRGBA(c3, 0.5))   //  rgba(0, 136, 255, 0.5)

Pure JS solution if it helps:如果有帮助,纯 JS 解决方案:

function hexToRGB(hex,alphaYes){
 var h = "0123456789ABCDEF";
 var r = h.indexOf(hex[1])*16+h.indexOf(hex[2]);
 var g = h.indexOf(hex[3])*16+h.indexOf(hex[4]);
 var b = h.indexOf(hex[5])*16+h.indexOf(hex[6]);
 if(alphaYes) return "rgba("+r+", "+g+", "+b+", 1)";
 else return "rgb("+r+", "+g+", "+b+")";
}

"alphaYes" is "true" or "false" depending upon whether you want the alpha or not. “alphaYes”是“true”或“false”,具体取决于您是否需要 alpha。

预习

If you want to convert hex to rgba then you can use this function, 如果要将十六进制转换为rgba,则可以使用此功能,

function hex2rgba_convert(hex,opacity){
 hex = hex.replace('#','');
 r = parseInt(hex.substring(0, hex.length/3), 16);
 g = parseInt(hex.substring(hex.length/3, 2*hex.length/3), 16);
 b = parseInt(hex.substring(2*hex.length/3, 3*hex.length/3), 16);

 result = 'rgba('+r+','+g+','+b+','+opacity/100+')';
 return result;
}

Here is details is hex to rgba 这是rgba的十六进制细节

Here is a function that returns rgb or rgba if you provide an alpha.如果您提供 alpha,这是一个返回 rgb 或 rgba 的函数。 The function also converts short hex color codes too.该功能还可以转换短的十六进制颜色代码。

function:功能:

function hexToRgb(hex, alpha) {
   hex   = hex.replace('#', '');
   var r = parseInt(hex.length == 3 ? hex.slice(0, 1).repeat(2) : hex.slice(0, 2), 16);
   var g = parseInt(hex.length == 3 ? hex.slice(1, 2).repeat(2) : hex.slice(2, 4), 16);
   var b = parseInt(hex.length == 3 ? hex.slice(2, 3).repeat(2) : hex.slice(4, 6), 16);
   if ( alpha ) {
      return 'rgba(' + r + ', ' + g + ', ' + b + ', ' + alpha + ')';
   }
   else {
      return 'rgb(' + r + ', ' + g + ', ' + b + ')';
   }
}

examples:例子:

hexToRgb('FF0000');// rgb(255, 0, 0)
hexToRgb('#FF0000');// rgb(255, 0, 0)
hexToRgb('#FF0000', 1);// rgba(255, 0, 0, 1)
hexToRgb('F00');// rgb(255, 0, 0)
hexToRgb('#F00');// rgb(255, 0, 0)
hexToRgb('#F00', 1);// rgba(255, 0, 0, 1)

ES6 modern, RegEx free, solution with error checking and constant arrow function, that returns null for errors. ES6现代,无 RegEx,具有错误检查和常量箭头功能的解决方案,错误返回 null。 If alpha is not given then the default value of one is used:如果未给出 alpha,则使用默认值 1:

const hexToRGB = (hex, alpha = 1) => {
    let parseString = hex;
    if (hex.startsWith('#')) {parseString = hex.slice(1, 7);}
    if (parseString.length !== 6) {return null;}
    const r = parseInt(parseString.slice(0, 2), 16);
    const g = parseInt(parseString.slice(2, 4), 16);
    const b = parseInt(parseString.slice(4, 6), 16);
    if (isNaN(r) || isNaN(g) || isNaN(b)) {return null;}
    return `rgba(${r}, ${g}, ${b}, ${alpha})`;
};

Note: It returns null for errors.注意:它返回null表示错误。 You may replace {return null;} with a throw statement: {throw "Not a valid hex color!";} , but then you should call it from within try-catch :您可以将{return null;}替换为 throw 语句: {throw "Not a valid hex color!";} ,但是您应该从try-catch中调用它:

hexToRGB("#3454r5") => null
hexToRGB("#345465") => rgba(52, 84, 101, 1)
hexToRGB("#345465", 0.5) => rgba(52, 84, 101, 0.5)

Here's a quick function that supports 3, 4, 6 and 8 character color codes:这是一个支持 3、4、6 和 8 个字符颜色代码的快速函数:

function hexToRGBA(hex) {
    // remove invalid characters
    hex = hex.replace(/[^0-9a-fA-F]/g, '');

    if (hex.length < 5) { 
        // 3, 4 characters double-up
        hex = hex.split('').map(s => s + s).join('');
    }

    // parse pairs of two
    let rgba = hex.match(/.{1,2}/g).map(s => parseInt(s, 16));

    // alpha code between 0 & 1 / default 1
    rgba[3] = rgba.length > 3 ? parseFloat(rgba[3] / 255).toFixed(2): 1;

    return 'rgba(' + rgba.join(', ') + ')';
}

Here's what it does.这就是它的作用。 It removes any non-hexadecimal characters.它删除任何非十六进制字符。 If the HEX is shorter than 5 (3 or 4) characters, it doubles each character.如果 HEX 短于 5(3 或 4)个字符,则将每个字符加倍。 It then splits the HEX into pairs of two characters and parses each pair to an integer.然后它将 HEX 拆分为两个字符对,并将每对字符解析为一个整数。 If there is an alpha HEX, it's parsed to a float from 0 to 1, otherwise it's defaulted to 1. The RGBA string is then formed by joining the array and returned.如果存在 alpha HEX,则解析为从 0 到 1 的浮点数,否则默认为 1。然后通过连接数组形成 RGBA 字符串并返回。

I liked the @AJFarkas answer and append the support for shortcut hex (#fff) to it我喜欢@AJFarkas 的答案,并将对快捷方式十六进制 (#fff) 的支持附加到它

 function hexToRGB(hex, alpha) { if (!hex || [4, 7].indexOf(hex.length) === -1) { return; // throw new Error('Bad Hex'); } hex = hex.substr(1); // if shortcuts (#F00) -> set to normal (#FF0000) if (hex.length === 3) { hex = hex.split('').map(function(el){ return el + el + ''; }).join(''); } var r = parseInt(hex.slice(0, 2), 16), g = parseInt(hex.slice(2, 4), 16), b = parseInt(hex.slice(4, 6), 16); if (alpha !== undefined) { return "rgba(" + r + ", " + g + ", " + b + ", " + alpha + ")"; } else { return "rgb(" + r + ", " + g + ", " + b + ")"; } } document.write(hexToRGB('#FF0000', 0.5)); document.write('<br>'); document.write(hexToRGB('#F00', 0.4));

Here's an ES2015+ version that's a little more defensive and handles the shorthand 3-digit syntax.这是一个 ES2015+ 版本,它更具防御性并处理速记 3 位语法。

/*
 * Takes a 3 or 6-digit hex color code, and an optional 0-255 numeric alpha value
 */
function hexToRGB(hex, alpha) {
  if (typeof hex !== 'string' || hex[0] !== '#') return null; // or return 'transparent'

  const stringValues = (hex.length === 4)
        ? [hex.slice(1, 2), hex.slice(2, 3), hex.slice(3, 4)].map(n => `${n}${n}`)
        : [hex.slice(1, 3), hex.slice(3, 5), hex.slice(5, 7)];
  const intValues = stringValues.map(n => parseInt(n, 16));

  return (typeof alpha === 'number')
    ? `rgba(${intValues.join(', ')}, ${alpha})`
    : `rgb(${intValues.join(', ')})`;
}

 function hexToRGB(hex, alpha) { var r = parseInt(hex.slice(1, 3), 16), g = parseInt(hex.slice(3, 5), 16), b = parseInt(hex.slice(5, 7), 16); if (alpha) { return "rgba(" + r + ", " + g + ", " + b + ", " + alpha + ")"; } else { return "rgb(" + r + ", " + g + ", " + b + ")"; } } hexToRGB('#FF0000', 0.5);

Actually, I like to use ES6 methods alongside preventing myself to using RegExp, RegExp is not safe, I don't trust it, the below answer is TypeScript, if you only need JavaScript just remove types:实际上,我喜欢使用 ES6 方法同时阻止自己使用 RegExp,RegExp 不安全,我不信任它,下面的答案是 TypeScript,如果你只需要 JavaScript,只需删除类型:

// TypeScript

const hex2rgba = (hex: string, alpha = 1): string => {
  if (alpha > 1 || alpha < 0) {
    throw new Error('alpha is not correct!');
  }

  const red = parseInt(hex.slice(1, 3), 16);
  const green = parseInt(hex.slice(3, 5), 16);
  const blue = parseInt(hex.slice(5, 7), 16);

  return `rgba(${red}, ${green}, ${blue}, ${alpha})`;
};

And another one based around bit shifting.另一个基于位移。

// hex can be a string in the format of "fc9a04", "0xfc9a04" or "#fc90a4" (uppercase digits are allowed) or the equivalent number
// alpha should be 0-1
const hex2rgb = (hex, alpha) => {
  const c = typeof(hex) === 'string' ? parseInt(hex.replace('#', ''), 16)  : hex;
  return `rgb(${c >> 16}, ${(c & 0xff00) >> 8}, ${c & 0xff}, ${alpha})`;
};

Try尝试

let hex2rgba= (hex,a)=> `rgba(${hex.substr(1).match(/../g).map(x=>+`0x${x}`)},${a})`

 /// hex - str eg "#abcdef"; a - alpha range 0-1; result eg "rgba(1,1,1,0)" let hex2rgba= (hex,a)=> `rgba(${hex.substr(1).match(/../g).map(x=>+`0x${x}`)},${a})`; function convert() { console.log(hex2rgba(inp.value,1)); }
 <input id="inp" value="#abcdef" > <button onclick="convert()">convert</button>

After so many years, just for the record, the DOM API does this convertion by default including the alpha.这么多年过去了,为了记录,DOM API 默认会进行这种转换,包括 alpha。 I mean if you do like;我的意思是,如果你喜欢;

tempElement.style.cssText = "color: #de1e7eaa";
console.log(tempElement.style.color) // <- rgb(222, 30, 126, 0.667)

you get RGB values as a string.您将 RGB 值作为字符串获取。 Then you may or not process it according to your needs.然后,您可以根据需要处理或不处理它。 We can leverage this opportunity if we are lazy enough.如果我们足够懒惰,我们可以利用这个机会。

 var color = "#de1e7eaa", // hex color code in string including alpha temp = document.createElement("i"), // just a temporary element rgbStr, rgbInt; temp.style.cssText = `color: ${color}`; // assign it to the style of the <i> element rgbStr = temp.style.color; rgbInt = Array.from(rgbStr.matchAll(/\d+\.?\d*/g), c=> +c[0]) // temp.style.color gives RGB string // then we convert it to Number if need be console.log(rgbStr); console.log(rgbInt);

Works with all shortcuts适用于所有快捷方式

Based on @kennebec 's answer, here is a solution which works with all hex shortcuts (#123, #1234, #123456, #12345678).根据@kennebec的回答,这是一个适用于所有十六进制快捷方式(#123、#1234、#123456、#12345678)的解决方案。

 const hex2rgba = (hex) => { let c = hex.substring(1).split(''); if (!/^#(([\dA-Fa-f]{3}){1,2}|([\dA-Fa-f]{4}){1,2})$/.test(hex)) { throw new Error('Your hexadecimal color is not correct.'); } switch (c.length) { case 3: c = [c[0] + c[0], c[1] + c[1], c[2] + c[2], 'ff']; break; case 4: c = [c[0]+c[0], c[1]+c[1], c[2]+c[2], c[3]+c[3]]; break; case 6: c = [c[0]+c[1], c[2]+c[3], c[4]+c[5], 'ff']; break; case 8: c = [c[0]+c[1], c[2]+c[3], c[4]+c[5], c[6]+c[7]]; break; } c = c.map((char) => parseInt(char, 16).toString()); c[3] = (Math.round((parseInt(c[3],10)/255)*100)/100).toString(); return c[3] === '1' ? `rgb( ${c[0]}, ${c[1]}, ${c[2]})` : `rgba(${c[0]}, ${c[1]}, ${c[2]}, ${c[3]})`; } //return a rgb or rgba value according to the alpha value console.log(hex2rgba('#af6')) console.log(hex2rgba('#af6f')) console.log(hex2rgba('#af64f576'))

Typescript Version打字稿版本

 const hex2rgba = (hex: string): string => { let c: string[] = hex.substring(1).split(''); if (!/^#(([\dA-Fa-f]{3}){1,2}|([\dA-Fa-f]{4}){1,2})$/.test(hex)) { throw new Error('Your hexadecimal color is not correct.'); } switch (c.length) { case 3: c = [c[0] + c[0], c[1] + c[1], c[2] + c[2], 'ff']; break; case 4: c = [c[0]+c[0], c[1]+c[1], c[2]+c[2], c[3]+c[3]]; break; case 6: c = [c[0]+c[1], c[2]+c[3], c[4]+c[5], 'ff']; break; case 8: c = [c[0]+c[1], c[2]+c[3], c[4]+c[5], c[6]+c[7]]; break; } c = c.map((char) => parseInt(char, 16).toString()); c[3] = (Math.round((parseInt(c[3],10)/255)*100)/100).toString(); return c[3] === '1' ? `rgb( ${c[0]}, ${c[1]}, ${c[2]})` : `rgba(${c[0]}, ${c[1]}, ${c[2]}, ${c[3]})`; }

Convert HEX with alpha (ahex) in to rgba.将带有 alpha (ahex) 的 HEX 转换为 rgba。

function ahex_to_rba(ahex) {
    //clean #
    ahex = ahex.substring(1, ahex.length);
    ahex = ahex.split('');

    var r = ahex[0] + ahex[0],
        g = ahex[1] + ahex[1],
        b = ahex[2] + ahex[2],
        a = ahex[3] + ahex[3];

    if (ahex.length >= 6) {
        r = ahex[0] + ahex[1];
        g = ahex[2] + ahex[3];
        b = ahex[4] + ahex[5];
        a = ahex[6] + (ahex[7] ? ahex[7] : ahex[6]);
    }

    var int_r = parseInt(r, 16),
        int_g = parseInt(g, 16),
        int_b = parseInt(b, 16),
        int_a = parseInt(a, 16);


    int_a = int_a / 255;

    if (int_a < 1 && int_a > 0) int_a = int_a.toFixed(2);

    if (int_a || int_a === 0)
        return 'rgba('+int_r+', '+int_g+', '+int_b+', '+int_a+')';
    return 'rgb('+int_r+', '+int_g+', '+int_b+')';
}

Try it yourself with snippet:用代码片段自己试试:

 function ahex_to_rba(ahex) { //clean # ahex = ahex.substring(1, ahex.length); ahex = ahex.split(''); var r = ahex[0] + ahex[0], g = ahex[1] + ahex[1], b = ahex[2] + ahex[2], a = ahex[3] + ahex[3]; if (ahex.length >= 6) { r = ahex[0] + ahex[1]; g = ahex[2] + ahex[3]; b = ahex[4] + ahex[5]; a = ahex[6] + (ahex[7] ? ahex[7] : ahex[6]); } var int_r = parseInt(r, 16), int_g = parseInt(g, 16), int_b = parseInt(b, 16), int_a = parseInt(a, 16); int_a = int_a / 255; if (int_a < 1 && int_a > 0) int_a = int_a.toFixed(2); if (int_a || int_a === 0) return 'rgba('+int_r+', '+int_g+', '+int_b+', '+int_a+')'; return 'rgb('+int_r+', '+int_g+', '+int_b+')'; } $(function() { $('#go').click(function() { $('p b').text(ahex_to_rba($('#hex').val())); }) });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input id="hex" type="text" value="#ffaaffaa"> <input id="go" type="button" value="Go"> <p>Result: <b></b></p>

Original Author原作者

Adding to @ElDoRado1239添加到@ElDoRado1239

For those that want to pass alpha value (typescript snippet):对于那些想要传递 alpha 值(打字稿片段)的人:

static hexToRGB(hex: string, alpha: number): string {
    var h = "0123456789ABCDEF";
    var r = h.indexOf(hex[1]) * 16 + h.indexOf(hex[2]);
    var g = h.indexOf(hex[3]) * 16 + h.indexOf(hex[4]);
    var b = h.indexOf(hex[5]) * 16 + h.indexOf(hex[6]);
    if (alpha) {
      return `rgba(${r}, ${g}, ${b}, ${alpha})`
    }

    return `rgba(${r}, ${g}, ${b})`;
  }

Modifying @kennebec 's solution to have alpha parameter修改@kennebec的解决方案以具有alpha参数

function hexToRgbA(hex, alpha=1){
    if(alpha > 1) alpha = 1;
    if(alpha < 0) alpha = 0;
    var c;
    if(/^#([A-Fa-f0-9]{3}){1,2}$/.test(hex)){
        c= hex.substring(1).split('');
        if(c.length== 3){
            c= [c[0], c[0], c[1], c[1], c[2], c[2]];
        }
        c= '0x'+c.join('');
        return 'rgba('+[(c>>16)&255, (c>>8)&255, c&255].join(',')+','+alpha+')';
    }
    throw new Error('Bad Hex');
}

hexToRgbA('#fce881', 0.6);

/* returned value: (String)
rgba(252,232,129,0.6)
*/

This should work for all use cases (short codes, long codes, with/without alpha)这应该适用于所有用例(短代码、长代码、带/不带 alpha)

hexToRGBA=q=>{
  q=q.replace('#', '')
  let l=q.length
  if(l!=3 && l!=4 && l!==6 && l!=8) return
  let red, green, blue, alpha, red_, green_, blue_, alpha_
  switch(l){
    case 3:
      red_     = q[0]+q[0]
      green_   = q[1]+q[1]
      blue_    = q[2]+q[2]
      alpha    = 255
    break
    case 4:
      red_     = q[0]+q[0]
      green_   = q[1]+q[1]
      blue_    = q[2]+q[2]
      alpha_   = q[3]+q[3]
      alpha    = +("0x"+alpha_)
    break
    case 6:
      red_     = q[0]+q[1]
      green_   = q[2]+q[3]
      blue_    = q[4]+q[5]
      alpha    = 255
    break
    case 8:
      red_     = q[0]+q[1]
      green_   = q[2]+q[3]
      blue_    = q[4]+q[5]
      alpha_   = q[6]+q[7]
      alpha    = +("0x"+alpha_)
    break
  }
  red    = +("0x"+red_)
  green  = +("0x"+green_)
  blue   = +("0x"+blue_)
  return [red, green, blue, alpha]
}

note: alpha is returned as the 4th element, range 0-255注意:alpha 作为第 4 个元素返回,范围 0-255

A clean and readable typescript way: (I could separate type, but it's easier to copy past like that)一种干净易读的 typescript 方式:(我可以分离类型,但这样更容易复制过去)

export const hexToRGB = (hex: string, alpha: number | undefined = 1) => {
  hex = hex.toUpperCase();

  const r = parseInt(hex.slice(1, 3), 16);
  const g = parseInt(hex.slice(3, 5), 16);
  const b = parseInt(hex.slice(5, 7), 16);

  return `rgba(${r}, ${g}, ${b}, ${alpha})`;
 }

No need to re-implement the wheel:无需重新实现轮子:

I'm just gonna put this right here:我只是把这个放在这里:

(str, alpha) => {


    if(!/^#([A-Fa-f0-9]{3}){1,2}$/.test(str))
      throw new Error('Bad hex')


    let c = str.substring(1).split('')
    if(c.length === 3) c = [c[0], c[0], c[1], c[1], c[2], c[2]];
    c = '0x'+c.join('');
    return `rgba(${(c>>16)&255}, ${(c>>8)&255}, ${c&255}, ${alpha})`;

};

Try This尝试这个

<div class="torgb" onclick="rgba();" style="background-color:#000; width:20px; height:20px;"></div>
<script>
function rgba(){
$('.torgb').attr('background-color','rgba(0,0,0,1)');
$('.torgb').attr('onclick','hex();');
}
function hex(){
$('.torgb').attr('background-color','#000');
$('.torgb').attr('onclick','rgba();');
}
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM