我有一个十六进制颜色的数组(动态值),我希望将浅色背景的字体颜色设置为黑色,为深色背景设置颜色为白色
/* array for example */
var colorHexCode = ["#ECECEC", "#FFF", "#F4F2ED"];
for (var i = 0; i < colorHexCode.length; i++) {
var ColorLayerDiv = document.createElement("div");
ColorLayerDiv.style.height = "10px";
ColorLayerDiv.style.backgroundColor = colorHexCode[i];
$('#Layers').append(ColorLayerDiv);
}
我想像这样自动设置字体颜色:
是否可以使用js或查询执行此操作?如果是,你能告诉我一个例子
答案 0 :(得分:1)
解决方案:
这段代码,来源:http://codepen.io/davidhalford/pen/ywEva;
threshold = 130; /* about half of 256. Lower threshold equals more dark text on dark background */
hRed = hexToR(hex);
hGreen = hexToG(hex);
hBlue = hexToB(hex);
function hexToR(h) {return parseInt((cutHex(h)).substring(0,2),16)}
function hexToG(h) {return parseInt((cutHex(h)).substring(2,4),16)}
function hexToB(h) {return parseInt((cutHex(h)).substring(4,6),16)}
function cutHex(h) {return (h.charAt(0)=="#") ? h.substring(1,7):h}
cBrightness = ((hRed * 299) + (hGreen * 587) + (hBlue * 114)) / 1000;
if (cBrightness > threshold){return "#000000";} else { return "#ffffff";}
}
感谢@jcubic
答案 1 :(得分:0)
在这里,您可以找到您的颜色是黑暗还是浅色:
(function ($) {
$.fn.lightOrDark = function () {
var r, b, g, hsp
, a = this.css('background-color');
if (a.match(/^rgb/)) {
a = a.match(/^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(\d+(?:\.\d+)?))?\)$/);
r = a[1];
g = a[2];
b = a[3];
} else {
a = +("0x" + a.slice(1).replace( // thanks to jed : http://gist.github.com/983661
a.length < 5 && /./g, '$&$&'
)
);
r = a >> 16;
b = a >> 8 & 255;
g = a & 255;
}
hsp = Math.sqrt( // HSP equation from http://alienryderflex.com/hsp.html
0.299 * (r * r) +
0.587 * (g * g) +
0.114 * (b * b)
);
if (hsp > 127.5) {
alert('light');
} else {
alert('dark');
}
}
})(jQuery);
答案 2 :(得分:0)
您可以处理颜色并计算亮度。
var colorHexCode = ["#ECECEC", "#FFF", "#F4F2ED","#777", "#FF0", '#00F'];
for (var i = 0; i < colorHexCode.length; i++) {
var ColorLayerDiv = document.createElement("div");
ColorLayerDiv.style.height = "20px";
ColorLayerDiv.style.backgroundColor = colorHexCode[i];
//text color
var c = colorHexCode[i];
var brightness = 0;
for(var j = 1; j< c.length; ++j){
var rgb = c[j];
if(c.length==4)
rgb += rgb;
else {
j+=1;
rgb += c[j];
}
var b = parseInt(rgb, 16);
brightness += b;
}
ColorLayerDiv.innerText = c;
ColorLayerDiv.style.color = brightness >= (255*3/2) ? 'black' : 'white';
$('#Layers').append(ColorLayerDiv);
}