使用下面的jQuery将获得元素背景颜色的RGB值:
$('#selector').css('backgroundColor');
有没有办法得到十六进制值而不是RGB?
使用下面的jQuery将获得元素背景颜色的RGB值:
$('#selector').css('backgroundColor');
有没有办法得到十六进制值而不是RGB?
当前回答
全案例(rgb, rgba, transparent…等)解决方案(coffeeScript)
rgb2hex: (rgb, transparentDefault=null)->
return null unless rgb
return rgb if rgb.indexOf('#') != -1
return transparentDefault || 'transparent' if rgb == 'rgba(0, 0, 0, 0)'
rgb = rgb.match(/^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(\d+))?\)$/);
hex = (x)->
("0" + parseInt(x).toString(16)).slice(-2)
'#' + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3])
其他回答
我的精简版
//函数将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)); }
下面是一个ES6 one liner,它不使用jQuery:
var rgb = document.querySelector('#selector').style['background-color'];
return '#' + rgb.substr(4, rgb.indexOf(')') - 4).split(',').map((color) => parseInt(color).toString(16).padStart(2, '0')).join('');
我漂亮的非标准解
HTML
<div id="selector" style="background-color:#f5b405"></div>
jQuery
$("#selector").attr("style").replace("background-color:", "");
结果
#f5b405
这个看起来好一点:
var rgb = $('#selector').css('backgroundColor').match(/\d+/g);
var r = parseInt(rgb[0], 10);
var g = parseInt(rgb[1], 10);
var b = parseInt(rgb[2], 10);
var hex = '#'+ r.toString(16) + g.toString(16) + b.toString(16);
更简洁的一句话:
var rgb = $('#selector').css('backgroundColor').match(/\d+/g);
var hex = '#'+ Number(rgb[0]).toString(16) + Number(rgb[1]).toString(16) + Number(rgb[2]).toString(16);
强制jQuery总是返回十六进制:
$.cssHooks.backgroundColor = {
get: function(elem) {
if (elem.currentStyle)
var bg = elem.currentStyle["backgroundColor"];
else if (window.getComputedStyle) {
var bg = document.defaultView.getComputedStyle(elem,
null).getPropertyValue("background-color");
}
if (bg.search("rgb") == -1) {
return bg;
} else {
bg = bg.match(/\d+/g);
function hex(x) {
return ("0" + parseInt(x).toString(16)).slice(-2);
}
return "#" + hex(bg[0]) + hex(bg[1]) + hex(bg[2]);
}
}
}
可读&& Reg-exp自由(无Reg-exp)
我创建了一个函数,它使用可读的基本函数,没有reg-exp。 该函数接受十六进制、rgb或rgba CSS格式的颜色,并返回十六进制表示。 编辑:有一个错误解析出rgba()格式,固定…
function getHexColor( color ){
//if color is already in hex, just return it...
if( color.indexOf('#') != -1 ) return color;
//leave only "R,G,B" :
color = color
.replace("rgba", "") //must go BEFORE rgb replace
.replace("rgb", "")
.replace("(", "")
.replace(")", "");
color = color.split(","); // get Array["R","G","B"]
// 0) add leading #
// 1) add leading zero, so we get 0XY or 0X
// 2) append leading zero with parsed out int value of R/G/B
// converted to HEX string representation
// 3) slice out 2 last chars (get last 2 chars) =>
// => we get XY from 0XY and 0X stays the same
return "#"
+ ( '0' + parseInt(color[0], 10).toString(16) ).slice(-2)
+ ( '0' + parseInt(color[1], 10).toString(16) ).slice(-2)
+ ( '0' + parseInt(color[2], 10).toString(16) ).slice(-2);
}