css代码如下:

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

js代码如下:

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

jquey貌似设置颜色,使用的是rgb格式的。

用以下这个function,把rgb转成“#xxxx”(HEX )格式。

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"

或者用这个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]);
}

5 thoughts on “jquery获取css color 值返回RGB

Leave a reply

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> 

required