使用以下jQuery将获取元素背景色的RGB值:
$('#selector').css('backgroundColor');
有没有办法获取十六进制值而不是RGB?
var hexDigits = new Array ("0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"); //Function to convert rgb color to hex format function rgb2hex(rgb) { rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/); return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]); } function hex(x) { return isNaN(x) ? "00" : hexDigits[(x - x % 16) / 16] + hexDigits[x % 16]; }
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]); }
一些浏览器已经返回十六进制的颜色(自Internet Explorer 8及更低版本开始)。如果需要处理这些情况,只需在函数内附加一个条件,例如@gfrobenius建议:
function rgb2hex(rgb) { if (/^#[0-9A-F]{6}$/i.test(rgb)) return 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]); }