Js converts the color value rgb to hexadecimal

Source: Internet
Author: User

When javascript uses dom to obtain the color values of backgroundColor and other styles, it obtains an rgb format value, such as rgb (, 12 ).
The following is a conversion function I wrote:


[Javascript]
Function RGBToHex (rgb ){
Var regexp =/^ rgb/([0-9] {})/,/s ([0-9 })/, /s ([0-9] {0, 3})/g;
Var re = rgb. replace (regexp, "$1 $2 $3"). split (""); // remove unnecessary parts using regular expressions
Var hexColor = "#"; var hex = ['0', '1', '2', '3', '4', '5', '6 ', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'];
For (var I = 0; I <3; I ++ ){
Var r = null; var c = re [I];
Var hexAr = [];
While (c> 16 ){
R = c % 16;
C = (c/16)> 0;
HexAr. push (hex [r]);
} HexAr. push (hex [c]);
HexColor + = hexAr. reverse (). join ('');
}
// Alert (hexColor)
Return hexColor;
}

From lazy Tom

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.