/** * Created by laixiangran on 2015/12/12. * String擴展 */(function() { // 十六進位顏色值的正則表達式 var reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/; // RG...
/** * Created by laixiangran on 2015/12/12. * String擴展 */ (function() { // 十六進位顏色值的正則表達式 var reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/; // RGB顏色轉換為16進位 if (typeof String.prototype.rgbToHex != "function") { String.prototype.rgbToHex = function() { var that = this; if (/^(rgb|RGB)/.test(that)) { var aColor = that.replace(/(?:\(|\)|rgb|RGB)*/g,"").split(","); var strHex = "#"; for (var i=0; i<aColor.length; i++) { var hex = Number(aColor[i]).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 j=0; j<aNum.length; j++) { numHex += (aNum[j]+aNum[j]); } return numHex; } }else{ return that; } }; } // 16進位顏色轉為RGB格式 if (typeof String.prototype.hexToRgb != "function") { String.prototype.hexToRgb = function() { var sColor = this.toLowerCase(); if (sColor && reg.test(sColor)) { if (sColor.length === 4) { var sColorNew = "#"; for (var i = 1; i < 4; i++) { sColorNew += sColor.slice(i,i+1).concat(sColor.slice(i,i+1)); } sColor = sColorNew; } // 處理六位的顏色值 var sColorChange = []; for (var j=1; j<7; j+=2) { sColorChange.push(parseInt("0x"+sColor.slice(j,j+2))); } return "RGB(" + sColorChange.join(",") + ")"; }else{ return sColor; } }; } // 移除字元串首尾空白 if (typeof String.prototype.trim != "function") { String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g, ""); }; } }());
參考
http://www.cnblogs.com/rubylouvre/archive/2009/09/18/1568794.html
http://www.cnblogs.com/rubylouvre/archive/2009/11/15/1603405.html