# 【原创】Javascript实现Web颜色值转换

2015/02/05 12:37

### rgb(a)颜色值转成十六进制颜色(hex)

``````<!-- lang: js -->
var rgbToHex = function(rgb) {
var rRgb = /rgb\((\d{1,3}),(\d{1,3}),(\d{1,3})\)/,
rRgba = /rgba\((\d{1,3}),(\d{1,3}),(\d{1,3}),([.\d]+)\)/,
r, g, b, a, rs = rgb.replace(/\s+/g, "").match(rRgb),
rsa = rgb.replace(/\s+/g, "").match(rRgba);
if (rs) {
r = (+rs[1]).toString(16);
r = r.length == 1 ? "0" + r : r;
g = (+rs[2]).toString(16);
g = g.length == 1 ? "0" + g : g;
b = (+rs[3]).toString(16);
b = b.length == 1 ? "0" + b : b;
return {hex: "#" + r + g + b, alpha: 100};
} else 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[4]) * 100
return {hex: "#" + r + g + b, alpha: Math.ceil(a)};
} else {
return {hex: rgb, alpha: 100};
}
};
``````

``````<!-- 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};
}
};
``````

### 十六进制颜色(hex)转成rgba格式

``````<!-- 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) + ')'
};
};
``````

1
38 收藏

### 作者的其它热门文章

very nice。我们不生成代码，我们是代码的搬用工
2015/02/11 09:52

2015/02/05 13:44

2 评论
38 收藏
1