Home > Web Front-end > JS Tutorial > body text

jQuery method to get the color value in the style_jquery

WBOY
Release: 2016-05-16 16:17:15
Original
992 people have browsed it

The example in this article describes how jQuery obtains the color value in the style. Share it with everyone for your reference. The specific analysis is as follows:

When I used jQuery to get the value of background-color in the style today, I found that the color value obtained in IE is in a different format than that displayed in Chrome and Firefox. In IE, it is displayed in HEX format [#ffff00], while in Chrome , Firefox displays [rgb(255,0,0)] in GRB format. Since the color values ​​need to be stored in the database, we want to unify the format of the color values ​​(in fact, they can be stored if they are not unified). After searching, I got a piece of code from a foreign website:

$.fn.getHexBackgroundColor = function() {
 var rgb = $(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]);
}
Copy after login

The above definition is a jQuery function. We can get the RGB value of the background-color of the tag id="bg" through $("#bg").getHexBackgroundColor();.

Let’s make a small modification, that is, add a judgment. If it is an IE browser, just get the value directly. If it is a non-IE browser, convert the value into RGB format:

$.fn.getHexBackgroundColor = function() {
 var rgb = $(this).css('background-color');
 if(!$.browser.msie){
  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;
}
Copy after login

I hope this article will be helpful to everyone’s jQuery programming.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template