Mic*_*rtz 64 javascript jquery colors
我的小提琴 - 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");
Run Code Online (Sandbox Code Playgroud)
目标

编辑:
TinyColor是一个伟大的颜色操作js库,可以完成我想要的所有内容.我想你们可能想尝试一下!- https://github.com/bgrins/TinyColor
ken*_*bec 125
//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)
*/
Run Code Online (Sandbox Code Playgroud)
AJF*_*kas 63
@ 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);Run Code Online (Sandbox Code Playgroud)
小智 21
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})`;
};
Run Code Online (Sandbox Code Playgroud)
用法:
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)
Run Code Online (Sandbox Code Playgroud)
小智 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;
}
Run Code Online (Sandbox Code Playgroud)
这里的细节是十六进制到rgba
清洁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})`;
}
}
Run Code Online (Sandbox Code Playgroud)
基于@ AJFarkas的回答.
如果有帮助,纯 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+")";
}
Run Code Online (Sandbox Code Playgroud)
"alphaYes" 是 "true" 或 "false",具体取决于您是否想要 alpha。

这是一个函数,如果你提供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 + ')';
}
}
Run Code Online (Sandbox Code Playgroud)
例子:
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)
Run Code Online (Sandbox Code Playgroud)
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})`;
};
Run Code Online (Sandbox Code Playgroud)
注意:它返回null错误.你可以{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)
Run Code Online (Sandbox Code Playgroud)
我喜欢 @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));Run Code Online (Sandbox Code Playgroud)
主要挑战是,截至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
}
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)})`
}
Run Code Online (Sandbox Code Playgroud)
请注意,可以通过以下任何一种方式向函数提供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)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
59389 次 |
| 最近记录: |