1 回答
TA贡献1775条经验 获得超11个赞
先转化为数组,再转化为想要的格式,提供如下代码供参考,最近刚修改的,新增了对透明度的支持
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);
}
};
正则写得不严谨,也不简洁,只能以后再折腾了。
添加回答
举报