代碼如下:
//十六進(jìn)制顏色值的正則表達(dá)式
var reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/;
/*RGB顏色轉(zhuǎn)換為16進(jìn)制*/
String.prototype.colorHex = function(){
var that = this;
if(/^(rgb|RGB)/.test(that)){
var aColor = that.replace(/(?:\(|\)|rgb|RGB)*/g,"").split(",");
var strHex = "#";
for(var i=0; i
var hex = Number(aColor).toString(16);
if(hex === "0"){
hex += hex;
}
strHex += hex;
}
if(strHex.length !== 7){
strHex = that;
}
return strHex;
}else if(reg.test(that)){
var aNum = that.replace(/#/,"").split("");
if(aNum.length === 6){
return that;
}else if(aNum.length === 3){
var numHex = "#";
for(var i=0; i
numHex += (aNum+aNum);
}
return numHex;
}
}else{
return that;
}};
/*16進(jìn)制顏色轉(zhuǎn)為RGB格式*/
String.prototype.colorRgb = function(){
var sColor = this.toLowerCase();
if(sColor && reg.test(sColor)){
if(sColor.length === 4){
var sColorNew = "#";
for(var i=1; i<4; i+=1){
sColorNew += sColor.slice(i,i+1).concat(sColor.slice(i,i+1));
}
sColor = sColorNew;
}
//處理六位的顏色值
var sColorChange = [];
for(var i=1; i<7; i+=2){
sColorChange.push(parseInt("0x"+sColor.slice(i,i+2)));
}
return "RGB(" + sColorChange.join(",") + ")";
}else{
return sColor;
}};
使用顏色轉(zhuǎn)換方法:
代碼如下:
ar sRgb = "RGB(23, 245, 56)" , sHex = "#34538b";
var sHexColor = sRgb.colorHex();
var sRgbColor = sHex.colorRgb();
聲明:本網(wǎng)頁內(nèi)容旨在傳播知識(shí),若有侵權(quán)等問題請及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com