/**
*
* @ Authors Benjamin (@ Benjamin)
* @ Date 2013-12-30 12:49:55
* @ Version 1.0
*/
I. Analysis:
* Common color formats:
* A) background-color: red
* B) background-color: # 00F
* C) background-color: # 0000F
* D) background-color: rgb (0, 0, 255)
II. Implementation:
/*** [Convert parserColor to hexadecimal format] * @ param {[String]} value [color value to be converted] * @ return {[String]} [return Conversion after the color value, # Sort FF format] */function parserColor (value) {varstr = "", arr = [], arri = "", I = 0, vlen = value. length, colorObj = {"black": "000000", "red": "0000FF", "blue": "FF0000", "white": "FFFFFF ", "yellow": "FFFF00", "orange": "FFA500"}; // rgb (255,) if (/rgb /. test (value) {arr = value. match (/\ d +/g); vlen = arr. length; for (; I < Vlen; I ++) {arri = parseInt (arr [I]); // convert to hexadecimal str + = arri <10? "0" + arri. toString (16): arri. toString (16) ;}} else if (/^ #/. test (value) {// # 00fif (vlen = 4) {str = value. replace (/[A-Za-z0-9]/g, "$ &");} else if (vlen = 7) {// # ff1_str = value. replace (/^ # ([A-Za-z0-9] *)/, "$1");} else {str = "FFFFFF" ;}} else {// red/orangevalue = value. toLowerCase (); str = colorObj [value]? ColorObj [value]: "FFFFFF"; // mismatch the default value is white} return "#" + str. toUpperCase ();}
Iii. instances:
console.log(parserColor("white"));//#FFFFFFFconsole.log(parserColor("#00f"));//#0000FFconsole.log(parserColor("rgb(0,0,255)"));//#0000FF
Reprinted, please respect originality, and indicate the source Benjamin-front-end attacker. The address on this page is http://blog.csdn.net/cuew1987/article/details/17679033,thank you!