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

The problem of jQuery obtaining the color value in CSS style, different solutions for different browser formats_jquery

WBOY
Release: 2016-05-16 17:34:02
Original
952 people have browsed it

When using jQuery to obtain the value of background-color in the style, I found that the obtained color value is displayed in HEX format [#ffff00] in versions below IE10, while in IE10, Chrome, and Firefox it is in GRB format. Display [rgb(255,0,0)]. Since the color value needs to be judged and processed, it is necessary to obtain a unified color format, preferably in HEX format, to facilitate processing. After searching, I got a piece of code from a foreign website:

Copy the code The code is as follows:

$.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]);
}

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

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

Copy code The code is as follows:

$.fn.getBackgroundColor = function() {
var rgb = $(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 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