我的小提琴 - http://jsbin.com/pitu/1/edit
我想尝试一个简单的十六进制到rgba转换。曾经使用的浏览器使用rgb作为默认颜色渲染颜色,所以当使用farbtastic颜色选择器时,我通过抓取十六进制值生成的背景颜色将十六进制值转换为rgb(默认情况下为rgb =简单转换)
我尝试将)
符号替换为, 1)
,但这没有用,所以我只是看看将rgb转换为rgba是如何工作的,我仍然遇到麻烦。
jquery
$('.torgb').val($('#color').css('background-color'));
$('.torgba').val().replace(/rgb/g,"rgba");
目标
编辑:
TinyColor是一个很棒的颜色操作js库,可以完成我想要的所有内容。我想你们可能想尝试一下! - https://github.com/bgrins/TinyColor
答案 0 :(得分:107)
//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)
*/
答案 1 :(得分:51)
@ 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);

答案 2 :(得分:13)
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})`;
};
用法:
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)
答案 3 :(得分:9)
如果你想将hex转换为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;
}
以下是hex to rgba
的详细信息答案 4 :(得分:8)
清理TypeScript版本:
hexToRGB(hex, alpha) {
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})`;
} else {
return `rgba(${r}, ${g}, ${b})`;
}
}
基于@ AJFarkas的回答。
答案 5 :(得分:7)
如果你提供alpha,这是一个返回rgb或rgba的函数。该函数也可以转换短的十六进制颜色代码。
<强>功能强>
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 + ')';
}
}
<强>的示例:强>
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)
答案 6 :(得分:6)
ES6 现代,RegEx免费,带有错误检查和常量箭头功能的解决方案,为错误返回null。如果未给出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})`;
};
注意:它会返回null
以查找错误。您可以使用throw语句{return null;}
替换{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)
答案 7 :(得分:3)
纯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”是“true”还是“false”,具体取决于您是否需要alpha。
答案 8 :(得分:3)
这是一款更具防御性的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(', ')})`;
}
答案 9 :(得分:3)
主要挑战是,截至2018年,HEX的形式多种多样。传统的6个字符形式,3个字符的缩短形式以及包括alpha的新的4和8个字符形式(到目前为止,仅部分支持)。以下函数可以处理任何十六进制格式。
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 / 256}
if (typeof alpha !== "undefined"){
if (1 < alpha && alpha <= 100) { return alpha / 100}
if (0 <= alpha && alpha <= 1) { return alpha }
}
return 1
}
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:
输出
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(c1, 50)) // rgba(255, 136, 0, 0.5)
console.log(hexToRGBA(c3, 0.5)) // rgba(0, 136, 255, 0.5)
console.log(hexToRGBA(c3, 50)) // rgba(0, 136, 255, 0.5)
console.log(hexToRGBA(c3, 120)) // rgba(0, 136, 255, 1)
const isValidHex: (hex:string) => boolean =
(hex) => /^#([A-Fa-f0-9]{3,4}){1,2}$/.test(hex)
const getChunksFromString : (str:string, chunkSize:number) => string[] | null =
(str, chunkSize) => str.match(new RegExp(`.{${chunkSize}}`, "g"))
const convertHexUnitTo256 : (hexStr:string) => number =
(hexStr) => parseInt(hexStr.repeat(2 / hexStr.length), 16)
const getAlphafloat : (a?:number, alpha?:number) => number =
(a, alpha) => {
if (a !== undefined) {return a / 256}
if (alpha !== undefined){
if (1 < alpha && alpha <= 100) { return alpha / 100}
if (0 <= alpha && alpha <= 1) { return alpha }
}
return 1
}
export const hexToRGBA : (hex:string, alpha?:number) => string =
(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) as string[]
const [r, g, b, a] = hexArr.map(convertHexUnitTo256)
return `rgba(${r}, ${g}, ${b}, ${getAlphafloat(a, alpha)})`
}
答案 10 :(得分:2)
我喜欢@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));
&#13;
答案 11 :(得分:1)
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);
答案 12 :(得分:1)
这是一个快速功能,支持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(', ') + ')';
}
这就是它的作用。它删除所有非十六进制字符。如果十六进制短于5个(3或4个)字符,则它将每个字符加倍。然后,它将HEX分成两个字符对,并将每个对解析为一个整数。如果存在alpha十六进制,则将其解析为从0到1的浮点数,否则默认为1。然后通过连接数组形成RGBA字符串并返回。
答案 13 :(得分:0)
实际上,我喜欢使用 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})`;
};
答案 14 :(得分:0)
我只想把它放在这里:
(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})`;
};
答案 15 :(得分:0)
无需重新安装轮子:
答案 16 :(得分:0)
添加到@ ElDoRado1239
对于那些希望传递alpha值的用户(打字稿片段):
const objs = {
"one":{
"title":"bla",
"amount":5,
"children":[
{
"title":"bla",
"identifier":"some text"
},
{
"title":"bla2",
"identifier":"some text2"
}
]
},
"two":{
"title":"bla",
"amount":5,
"children":[
{
"title":"bla",
"identifier":"some text"
},
{
"title":"bla2",
"identifier":"some text2"
}
]
}
};
const newObjs = Object.keys(objs).reduce( (acc, curr) => {
const updatedObj = { ...objs[curr], items: objs[curr].children };
delete updatedObj.children
acc[curr] = { ...updatedObj };
return acc;
}, {});
console.log(newObjs)
答案 17 :(得分:0)
将带有alpha(ahex)的十六进制转换为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+')';
}
使用代码段尝试一下:
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>
答案 18 :(得分:0)
尝试
// hex - str e.g. "#abcdef"; a - alpha range 0-1; result e.g. "rgba(1,1,1,0)"
let hex2rgba= (hex,a)=> `rgb(${hex.substr(1).match(/../g).map(x=>+`0x${x}`)},${a})`
/// hex - str e.g. "#abcdef"; a - alpha range 0-1; result e.g. "rgba(1,1,1,0)"
let hex2rgba= (hex,a)=> `rgb(${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>
答案 19 :(得分:0)
另外一个基于位移。
// 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})`;
};
答案 20 :(得分:-8)
试试这个
<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>