大家讲道理2017-04-11 11:43:35
先转化为数组,再转化为想要的格式,提供如下代码供参考,最近刚修改的,新增了对透明度的支持
var toArray = function(value) {
if (/^#[A-Za-z0-9]{3}$/.test(value)) {
value = value.replace(/#/, "");
var arr = [];
arr[0] = parseInt(value.substr(0, 1) + value.substr(0, 1), 16);
arr[1] = parseInt(value.substr(1, 1) + value.substr(1, 1), 16);
arr[2] = parseInt(value.substr(2, 1) + value.substr(2, 1), 16);
arr[3] = 1;
return arr;
}
if (/^#[A-Za-z0-9]{6}$/.test(value)) {
value = value.replace(/#/, "");
var arr = [];
arr[0] = parseInt(value.substr(0, 2), 16);
arr[1] = parseInt(value.substr(2, 2), 16);
arr[2] = parseInt(value.substr(4, 2), 16);
arr[3] = parseInt(1);
return arr;
}
if (/^#[A-Za-z0-9]{8}$/.test(value)) {
value = value.replace(/#/, "");
var arr = [];
arr[0] = parseInt(value.substr(2, 2), 16);
arr[1] = parseInt(value.substr(4, 2), 16);
arr[2] = parseInt(value.substr(6, 2), 16);
arr[3] = parseInt(value.substr(0, 2), 16) / 255;
return arr;
}
if (/^rgb\([0-9,\.\s]+\)$/.test(value)) {
var arr = value.replace(/(rgb\(|\))/gi, "").split(/,\s*/);
arr[0] = parseInt(arr[0]);
arr[1] = parseInt(arr[1]);
arr[2] = parseInt(arr[2]);
arr[3] = 1;
return arr;
}
if (/^rgba\([0-9,\.\s]+\)$/.test(value)) {
var arr = value.replace(/(rgb\(|\))/gi, "").split(/,\s*/);
arr[0] = parseInt(arr[0]);
arr[1] = parseInt(arr[1]);
arr[2] = parseInt(arr[2]);
arr[3] = parseInt(arr[3]);
return arr;
}
return null;
},
toHex = function(num) {
var hex;
num = (num >= 0 && num <= 255) ? num: 0;
hex = num.toString(16);
return hex.length === 2 ? hex: '0' + hex;
},
toValue = {
rgb: function(arr) {
return 'rgb(' + arr[0] + ',' + arr[1] + ',' + arr[2] + ')';
},
rgba: function(arr) {
return 'rgb(' + arr[0] + ',' + arr[1] + ',' + arr[2] + ',' + arr[3] + ')';
},
hex6: function(arr) {
return '#' + toHex(arr[0]) + toHex(arr[1]) + toHex(arr[2]);
},
hex8: function(arr) {
return '#' + toHex(arr[0]) + toHex(arr[1]) + toHex(arr[2]) + toHex(arr[3] * 255);
}
};
正则写得不严谨,也不简洁,只能以后再折腾了。
伊谢尔伦2017-04-11 11:43:35
就是16进制表示与10进制表示的转换
一个 rgb 颜色值本质代表 rgb 三个颜色分量的值
如:
#ffff00
=>{
r = 0xff = 255
g = 0xff = 255
b = 0x00 = 0
}
=> rgb(255,255,0)