Home  >  Article  >  Web Front-end  >  jquery method to get the color value of css and return RGB_jquery

jquery method to get the color value of css and return RGB_jquery

WBOY
WBOYOriginal
2016-05-16 15:24:501814browse

The example in this article describes how jquery obtains the color value of css and returns RGB. Share it with everyone for your reference, the details are as follows:

The css code is as follows:

a, a:link, a:visited { color:#4188FB; }
a:active, a:focus, a:hover { color:#FFCC00; }

js code is as follows:

var link_col = $("a:link").css("color");
alert(link_col); // returns rgb(65, 136, 251)

jquey seems to set the color, using rgb format.

Use the following function to convert rgb to "#xxxx" (HEX) format.

var rgbString = "rgb(0, 70, 255)"; // get this in whatever way.
var parts = rgbString.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
// parts now should be ["rgb(0, 70, 255", "0", "70", "255"]
delete (parts[0]);
for (var i = 1; i <= 3; ++i) {
parts[i] = parseInt(parts[i]).toString(16);
if (parts[i].length == 1) parts[i] = '0' + parts[i];
}
var hexString = parts.join(''); // "0070ff"

Or use this function

function rgb2hex(rgb) {
rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
function hex(x) {
return ("0" + parseInt(x).toString(16)).slice(-2);
}
return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]);
}

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

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