Home >Web Front-end >JS Tutorial >jQuery gets the background color attribute value/color value in the style_jquery

jQuery gets the background color attribute value/color value in the style_jquery

WBOY
WBOYOriginal
2016-05-16 17:46:281364browse

When I used jQuery to obtain the value of background-color in the style, I found that the obtained color value was in a different format in IE than in Chrome and Firefox. IE displayed #ffff00 in HEX format, while Chrome and Firefox displayed it as #ffff00. Display 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

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

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

Let’s do a little The modification is to 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:
Copy code The code is as follows:

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

jQuery gets the attribute value in the style sheet
Copy code The code is as follows:


aaaa




< div id="left">





Statement:
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
Previous article:Jquery selects a column of the table and sorts the table implementation principle_jqueryNext article:Jquery selects a column of the table and sorts the table implementation principle_jquery

Related articles

See more