原文:http://my.oschina.net/mailzwj/blog/375624
<!-- lang: js -->
var rgbToHex = function(rgb) {
var rRgba = /rgba?\((\d{1,3}),(\d{1,3}),(\d{1,3})(,([.\d]+))?\)/,
r, g, b, a,
rsa = rgb.replace(/\s+/g, "").match(rRgba);
if (rsa) {
r = (+rsa[1]).toString(16);
r = r.length == 1 ? "0" + r : r;
g = (+rsa[2]).toString(16);
g = g.length == 1 ? "0" + g : g;
b = (+rsa[3]).toString(16);
b = b.length == 1 ? "0" + b : b;
a = (+(rsa[5] ? rsa[5] : 1)) * 100
return {hex: "#" + r + g + b, alpha: Math.ceil(a)};
} else {
return {hex: rgb, alpha: 100};
}
};
<!-- lang: js -->
var hexToRgba = function(hex, al) {
var hexColor = /^#/.test(hex) ? hex.slice(1) : hex,
alp = hex === 'transparent' ? 0 : Math.ceil(al),
r, g, b;
hexColor = /^[0-9a-f]{3}|[0-9a-f]{6}$/i.test(hexColor) ? hexColor : 'fffff';
if (hexColor.length === 3) {
hexColor = hexColor.replace(/(\w)(\w)(\w)/gi, '$1$1$2$2$3$3');
}
r = hexColor.slice(0, 2);
g = hexColor.slice(2, 4);
b = hexColor.slice(4, 6);
r = parseInt(r, 16);
g = parseInt(g, 16);
b = parseInt(b, 16);
return {
hex: '#' + hexColor,
alpha: alp,
rgba: 'rgba(' + r + ', ' + g + ', ' + b + ', ' + (alp / 100).toFixed(2) + ')'
};
};
原作者博客:
http://www.seejs.com/