使用下面的jQuery将获得元素背景颜色的RGB值:
$('#selector').css('backgroundColor');
有没有办法得到十六进制值而不是RGB?
使用下面的jQuery将获得元素背景颜色的RGB值:
$('#selector').css('backgroundColor');
有没有办法得到十六进制值而不是RGB?
当前回答
函数返回以十六进制表示的元素的背景色。
function getBgColorHex(elem){
var color = elem.css('background-color')
var hex;
if(color.indexOf('#')>-1){
//for IE
hex = color;
} else {
var rgb = color.match(/\d+/g);
hex = '#'+ ('0' + parseInt(rgb[0], 10).toString(16)).slice(-2) + ('0' + parseInt(rgb[1], 10).toString(16)).slice(-2) + ('0' + parseInt(rgb[2], 10).toString(16)).slice(-2);
}
return hex;
}
使用的例子:
$('#div1').click(function(){
alert(getBgColorHex($(this));
}
斯菲德尔
其他回答
函数返回以十六进制表示的元素的背景色。
function getBgColorHex(elem){
var color = elem.css('background-color')
var hex;
if(color.indexOf('#')>-1){
//for IE
hex = color;
} else {
var rgb = color.match(/\d+/g);
hex = '#'+ ('0' + parseInt(rgb[0], 10).toString(16)).slice(-2) + ('0' + parseInt(rgb[1], 10).toString(16)).slice(-2) + ('0' + parseInt(rgb[2], 10).toString(16)).slice(-2);
}
return hex;
}
使用的例子:
$('#div1').click(function(){
alert(getBgColorHex($(this));
}
斯菲德尔
由于问题是使用JQuery,下面是一个基于Daniel Elliott代码的JQuery插件:
$.fn.cssAsHex = function(colorProp) {
var hexDigits = '0123456789abcdef';
function hex(x) {
return isNaN(x) ? '00' : hexDigits[(x - x % 16) / 16] + hexDigits[x % 16];
};
// Convert RGB color to Hex format
function rgb2hex(rgb) {
var rgbRegex = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
return '#' + hex(rgbRegex[1]) + hex(rgbRegex[2]) + hex(rgbRegex[3]);
};
return rgb2hex(this.css(colorProp));
};
像这样使用它:
var hexBackgroundColor = $('#myElement').cssAsHex('background-color');
我的精简版
//函数将rgb颜色转换为十六进制格式 函数rgb2hex(rgb) { If (/^#/.test(rgb))返回rgb;// If返回十六进制颜色 设re = /\d+/g; 让十六进制= x = > (x > > 4) .toString (16) + (x & 0 xf) .toString (16); 返回“#”+十六进制(re.exec (rgb)) +十六进制(re.exec (rgb)) +十六进制(re.exec (rgb)); }
短
// c - color str e.g."rgb(12,233,43)", result color hex e.g. "#0ce92b"
let rgb2hex=c=>'#'+c.match(/\d+/g).map(x=>(+x).toString(16).padStart(2,0)).join``
// RGB -颜色STR,例如" RGB(12,233,43)",结果颜色十六进制,例如“# 0 ce92b” 让rgb2hex = c = > ' # ' + c.match (\ d + / g) . map (x = > (+ x) .toString (16) .padStart (2,0)) . join ' ' console.log (rgb2hex(“rgb(12233年,43”);
嗨,这是我的解决方案后,获得元素的颜色与Javascript
function rgb_hex(rgb_string_js){ //example: "rgb(102,54,255)"
var new_rgb_list = rgb_string_js.replace("rgb(","").replace(")","").split(",");
return ("#" + parseInt(new_rgb_list[0]).toString(16) + parseInt(new_rgb_list[1]).toString(16) + parseInt(new_rgb_list[2]).toString(16));
}