Javascript实现Web颜色值转换

0
0
0
1. 云栖社区>
2. 博客>
3. 正文

## Javascript实现Web颜色值转换

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

``` 1 var rgbToHex = function(rgb) {
2     var rRgb = /rgb\((\d{1,3}),(\d{1,3}),(\d{1,3})\)/,
3         rRgba = /rgba\((\d{1,3}),(\d{1,3}),(\d{1,3}),([.\d]+)\)/,
4         r, g, b, a, rs = rgb.replace(/\s+/g, "").match(rRgb),
5         rsa = rgb.replace(/\s+/g, "").match(rRgba);
6     if (rs) {
7         r = (+rs[1]).toString(16);
8         r = r.length == 1 ? "0" + r : r;
9         g = (+rs[2]).toString(16);
10         g = g.length == 1 ? "0" + g : g;
11         b = (+rs[3]).toString(16);
12         b = b.length == 1 ? "0" + b : b;
13         return {hex: "#" + r + g + b, alpha: 100};
14     } else if (rsa) {
15         r = (+rsa[1]).toString(16);
16         r = r.length == 1 ? "0" + r : r;
17         g = (+rsa[2]).toString(16);
18         g = g.length == 1 ? "0" + g : g;
19         b = (+rsa[3]).toString(16);
20         b = b.length == 1 ? "0" + b : b;
21         a = (+rsa[4]) * 100
22         return {hex: "#" + r + g + b, alpha: Math.ceil(a)};
23     } else {
24         return {hex: rgb, alpha: 100};
25     }
26 };```

``` 1 var rgbToHex = function(rgb) {
2     var rRgba = /rgba?\((\d{1,3}),(\d{1,3}),(\d{1,3})(,([.\d]+))?\)/,
3         r, g, b, a,
4         rsa = rgb.replace(/\s+/g, "").match(rRgba);
5     if (rsa) {
6         r = (+rsa[1]).toString(16);
7         r = r.length == 1 ? "0" + r : r;
8         g = (+rsa[2]).toString(16);
9         g = g.length == 1 ? "0" + g : g;
10         b = (+rsa[3]).toString(16);
11         b = b.length == 1 ? "0" + b : b;
12         a = (+(rsa[5] ? rsa[5] : 1)) * 100
13         return {hex: "#" + r + g + b, alpha: Math.ceil(a)};
14     } else {
15         return {hex: rgb, alpha: 100};
16     }
17 };```

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

``` 1 var hexToRgba = function(hex, al) {
2     var hexColor = /^#/.test(hex) ? hex.slice(1) : hex,
3         alp = hex === 'transparent' ? 0 : Math.ceil(al),
4         r, g, b;
5     hexColor = /^[0-9a-f]{3}|[0-9a-f]{6}\$/i.test(hexColor) ? hexColor : 'fffff';
6     if (hexColor.length === 3) {
7         hexColor = hexColor.replace(/(\w)(\w)(\w)/gi, '\$1\$1\$2\$2\$3\$3');
8     }
9     r = hexColor.slice(0, 2);
10     g = hexColor.slice(2, 4);
11     b = hexColor.slice(4, 6);
12     r = parseInt(r, 16);
13     g = parseInt(g, 16);
14     b = parseInt(b, 16);
15     return {
16         hex: '#' + hexColor,
17         alpha: alp,
18         rgba: 'rgba(' + r + ', ' + g + ', ' + b + ', ' + (alp / 100).toFixed(2) + ')'
19     };
20 };```

+ 关注