如何根据背景颜色改变文本颜色?

时间:2022-05-29 19:55:30

I'm looking for a way, with jQuery ideally, to determine the correct text color, based on the brightness of the background color?

我正在寻找一种方法,理想的使用jQuery,根据背景颜色的亮度确定正确的文本颜色?

E.g. white background, black text colour. I believe this could be done crudely with adding the HEX value and guesstimating but does anyone know a better way or jQuery way to do this?

白色背景,黑色文字颜色。我相信这可以通过添加十六进制值和猜测来实现,但是有人知道更好的方法或者jQuery方法吗?

1 个解决方案

#1


31  

You can try inverting the hex value of the color. So #FFFFFF becomes #000000 and #AAAAAA becomes #555555. Of course, this method falls through when you have #888888 which when inverted, gives you #777777 (they don't contrast as much).

你可以尝试逆变颜色的十六进制值。所以# ffff变成#000000,#AAAAAA变成#555555。当然,当你有#8888时,这个方法就会失效,当你有#7777时,它就会倒过来,给你#7777。

This blog post describes another way (they only use black or white for the foreground color, depending on the background color). I've translated it into Javascript:

这篇博客描述了另一种方式(他们只使用黑色或白色作为前景颜色,取决于背景颜色)。我把它翻译成Javascript:

function idealTextColor(bgColor) {

   var nThreshold = 105;
   var components = getRGBComponents(bgColor);
   var bgDelta = (components.R * 0.299) + (components.G * 0.587) + (components.B * 0.114);

   return ((255 - bgDelta) < nThreshold) ? "#000000" : "#ffffff";   
}

function getRGBComponents(color) {       

    var r = color.substring(1, 3);
    var g = color.substring(3, 5);
    var b = color.substring(5, 7);

    return {
       R: parseInt(r, 16),
       G: parseInt(g, 16),
       B: parseInt(b, 16)
    };
}

#1


31  

You can try inverting the hex value of the color. So #FFFFFF becomes #000000 and #AAAAAA becomes #555555. Of course, this method falls through when you have #888888 which when inverted, gives you #777777 (they don't contrast as much).

你可以尝试逆变颜色的十六进制值。所以# ffff变成#000000,#AAAAAA变成#555555。当然,当你有#8888时,这个方法就会失效,当你有#7777时,它就会倒过来,给你#7777。

This blog post describes another way (they only use black or white for the foreground color, depending on the background color). I've translated it into Javascript:

这篇博客描述了另一种方式(他们只使用黑色或白色作为前景颜色,取决于背景颜色)。我把它翻译成Javascript:

function idealTextColor(bgColor) {

   var nThreshold = 105;
   var components = getRGBComponents(bgColor);
   var bgDelta = (components.R * 0.299) + (components.G * 0.587) + (components.B * 0.114);

   return ((255 - bgDelta) < nThreshold) ? "#000000" : "#ffffff";   
}

function getRGBComponents(color) {       

    var r = color.substring(1, 3);
    var g = color.substring(3, 5);
    var b = color.substring(5, 7);

    return {
       R: parseInt(r, 16),
       G: parseInt(g, 16),
       B: parseInt(b, 16)
    };
}