How does jQuery obtain the color values in CSS Styles? Different browser formats

Source: Internet
Author: User

When jQuery is used to obtain the value of background-color in the style, the obtained color value is displayed in HEX format in IE10 or earlier versions [# ffff00], while IE10, chrome and Firefox display [rgb (255, 0, 0)] in GRB format. To determine the color value, you need to obtain a uniform color format, preferably in HEX format, easy to handle. Search for a piece of code from a foreign website:

Copy codeThe Code is as follows: $. fn. getHexBackgroundColor = function (){
Var rgb = background (this).css ('background-color ');
Rgb = rgb. match (/^ rgb \ (\ d +), \ s * (\ d +), \ s * (\ d +) \) $ /);
Function hex (x) {return ("0" + parseInt (x). toString (16). slice (-2 );}
Return rgb = "#" + hex (rgb [1]) + hex (rgb [2]) + hex (rgb [3]);
}

The above defines a jQuery function. We can use $ ("# bg"). getHexBackgroundColor (); to obtain the RGB value of background-color with the tag id = "bg.

The following is a small modification, that is, adding a judgment. If the HEX value is displayed (less than IE10), the value is taken directly. If it is not an IE browser, the value is converted to the RGB format:

Copy codeThe Code is as follows: $. fn. getBackgroundColor = function (){
Var rgb = background (this).css ('background-color ');
If (rgb> = 0) return rgb; // if it is a hex value, return directly
Else {
Rgb = rgb. match (/^ rgb \ (\ d +), \ s * (\ d +), \ s * (\ d +) \) $ /);
Function hex (x) {return ("0" + parseInt (x). toString (16). slice (-2 );}
Rgb = "#" + hex (rgb [1]) + hex (rgb [2]) + hex (rgb [3]);
}
Return rgb;
}
Related Article

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.