我创建了一个使用可读基本功能而没有reg-exps的函数 . 该函数接受十六进制的颜色,rgb or rgba CSS格式并返回十六进制表示 . EDIT: 解析出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);
}
0
从bootstrap颜色选择器采取的颜色类
// Color object
var Color = function(val) {
this.value = {
h: 1,
s: 1,
b: 1,
a: 1
};
this.setColor(val);
};
Color.prototype = {
constructor: Color,
//parse a string to HSB
setColor: function(val){
val = val.toLowerCase();
var that = this;
$.each( CPGlobal.stringParsers, function( i, parser ) {
var match = parser.re.exec( val ),
values = match && parser.parse( match ),
space = parser.space||'rgba';
if ( values ) {
if (space === 'hsla') {
that.value = CPGlobal.RGBtoHSB.apply(null, CPGlobal.HSLtoRGB.apply(null, values));
} else {
that.value = CPGlobal.RGBtoHSB.apply(null, values);
}
return false;
}
});
},
setHue: function(h) {
this.value.h = 1- h;
},
setSaturation: function(s) {
this.value.s = s;
},
setLightness: function(b) {
this.value.b = 1- b;
},
setAlpha: function(a) {
this.value.a = parseInt((1 - a)*100, 10)/100;
},
// HSBtoRGB from RaphaelJS
// https://github.com/DmitryBaranovskiy/raphael/
toRGB: function(h, s, b, a) {
if (!h) {
h = this.value.h;
s = this.value.s;
b = this.value.b;
}
h *= 360;
var R, G, B, X, C;
h = (h % 360) / 60;
C = b * s;
X = C * (1 - Math.abs(h % 2 - 1));
R = G = B = b - C;
h = ~~h;
R += [C, X, 0, 0, X, C][h];
G += [X, C, C, X, 0, 0][h];
B += [0, 0, X, C, C, X][h];
return {
r: Math.round(R*255),
g: Math.round(G*255),
b: Math.round(B*255),
a: a||this.value.a
};
},
toHex: function(h, s, b, a){
var rgb = this.toRGB(h, s, b, a);
return '#'+((1 << 24) | (parseInt(rgb.r) << 16) | (parseInt(rgb.g) << 8) | parseInt(rgb.b)).toString(16).substr(1);
},
toHSL: function(h, s, b, a){
if (!h) {
h = this.value.h;
s = this.value.s;
b = this.value.b;
}
var H = h,
L = (2 - s) * b,
S = s * b;
if (L > 0 && L <= 1) {
S /= L;
} else {
S /= 2 - L;
}
L /= 2;
if (S > 1) {
S = 1;
}
return {
h: H,
s: S,
l: L,
a: a||this.value.a
};
}
};
如何使用
var color = new Color("RGB(0,5,5)");
color.toHex()
2
这个看起来好一点:
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]);
}
}
}
2
以十六进制返回元素的背景颜色的函数 .
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;
}
17 回答
更新了@ErickPetru以获得rgba兼容性:
我更新了正则表达式以匹配alpha值(如果已定义),但不使用它 .
这是一个不使用jQuery的ES6 one liner:
这是一个也检查透明的版本,我需要这个,因为我的对象是将结果插入到样式属性中,其中十六进制颜色的透明版本实际上是单词“transparent” .
(Source)
这是我根据@Matt建议写的更清洁的解决方案:
某些浏览器已将颜色返回为十六进制(从Internet Explorer 8及更低版本开始) . 如果你需要处理这些情况,只需在函数内附加一个条件,比如@gfrobenius建议:
如果你正在使用jQuery并想要一个更完整的方法,你可以使用自jQuery 1.4.3以来的CSS Hooks,正如我在回答这个问题时所展示的那样:Can I force jQuery.css("backgroundColor") returns on hexadecimal format?
使用时,大多数浏览器似乎都会返回RGB值:
只有I.E(到目前为止只测试了6个)返回Hex值 .
要避免在I.E中出现错误消息,可以将函数包装在if语句中:
可读&& Reg-exp免费(无Reg-exp)
我创建了一个使用可读基本功能而没有reg-exps的函数 .
该函数接受十六进制的颜色,rgb or rgba CSS格式并返回十六进制表示 .
EDIT: 解析出rgba()格式有一个错误,已修复...
从bootstrap颜色选择器采取的颜色类
如何使用
这个看起来好一点:
一个更简洁的单行:
强制jQuery总是返回十六进制:
以十六进制返回元素的背景颜色的函数 .
用法示例:
jsfiddle
相同答案like @Jim F answer但 ES6 语法,所以,更少说明:
只是添加到@ Justin的答案上面..
它应该是
由于上面的解析int函数截断前导零,因此产生5或4个字母的错误颜色代码可能是...即对于rgb(216,160,10),它产生#d8a0a,而它应该是#d8a00a .
谢谢
这是我发现的一个解决方案,它不会在IE中引发脚本错误:http://haacked.com/archive/2009/12/29/convert-rgb-to-hex.aspx
由于问题是使用JQuery,这里是一个基于Daniel Elliott代码的JQuery插件:
使用它像:
这是我的解决方案,也通过使用参数来检查touppercase并检查提供的字符串中的其他可能的空格和大小写 .
在jsfiddle
jsperf上的速度比较
进一步的改进可能是
rgb
字符串Steven Pribilinskiy的答案会降低前导零,例如#ff0000成为#ff00 .
一种解决方案是在最后2位数后附加前导0和子串 .
我美丽的非标准解决方案
HTML
jQuery
Result