如何基于动态更改的背景颜色动态更改文本颜色

时间:2019-04-20 09:52:43

标签: javascript html css

我正在建立一个新的网站,需要我的文本根据不断变化的背景颜色来更改颜色,以保持对比度。我在网上搜寻了不涉及Sass的答案,但没有一个起作用...

我尝试了一些JavaScript,但是只有当背景是您手动更改的固定颜色时,它们才起作用。

我当前的文件: https://codepen.io/jonathanlee/pen/wZXvRY

var color = function getRandomColor() {
  var letters = '0123456789ABCDEF'.split('');
  var color = '#';
  for (var i = 0; i < 6; i++) {
    color += letters[Math.floor(Math.random() * 16)];
  }
  return color;
}
setInterval(function() {
  document.getElementById("test").style.backgroundColor = color(); //() to execute the function!
}, 3000);

var ww = function isDarkColor(rgb) {
  return Math.round((
    parseInt(rgb[0], 10) * 299 +
    parseInt(rgb[1], 10) * 587 +
    parseInt(rgb[2], 10) * 114) / 1000) <= 140
}

if (ww <= 140) {
  document.getElementById("test").style.color = '#fff';
} else {
  document.getElementById("test").style.color = '#000';
}

我尝试过但无法使用的其他解决方案之一:http://jsfiddle.net/QkSva/

function isDark(color) {
  var match = /rgb\((\d+).*?(\d+).*?(\d+)\)/.exec(color);
  return (match[1] & 255) +
    (match[2] & 255) +
    (match[3] & 255) <
    3 * 256 / 2;
}
$('div').each(function() {
  console.log($(this).css("background-color"))
  $(this).css("color", isDark($(this).css("background-color")) ? 'white' : 'black');
});

真实示例是我正在使用的网站https://nepmelbourne.com/q上的备用首页。我有一个动态的背景,但是有些颜色与白色文本不能很好地形成对比。

1 个答案:

答案 0 :(得分:0)

一种方法是将背景颜色的反色设置为文本,如下所示,

function invertColor(hex) {   
    if (hex.indexOf('#') === 0) {
            hex = hex.slice(1);
        }
        // convert 3-digit hex to 6-digits.
        if (hex.length === 3) {
            hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2];
        }
        if (hex.length !== 6) {
            throw new Error('Invalid HEX color.');
        }
        // invert color components
        var r = (255 - parseInt(hex.slice(0, 2), 16)).toString(16),
            g = (255 - parseInt(hex.slice(2, 4), 16)).toString(16),
            b = (255 - parseInt(hex.slice(4, 6), 16)).toString(16);
        // pad each with zeros and return
        return '#' + padZero(r) + padZero(g) + padZero(b);
}

function padZero(str, len) {
    len = len || 2;
    var zeros = new Array(len).join('0');
    return (zeros + str).slice(-len);
}

var color = function getRandomColor() {
    var letters = '0123456789ABCDEF'.split('');
    var color = '#';
    for (var i = 0; i < 6; i++) {
        color += letters[Math.floor(Math.random() * 16)];
    }
    return color;
}

setInterval(function() {
    var bgColor = color();
    var textColor = invertColor(bgColor);
    document.getElementById("test").style.backgroundColor = bgColor; //() to execute the function!
    document.getElementById("test").style.color = textColor;
}, 3000);
<div id="test">This is some text</div>

取自How can I generate the opposite color according to current color?

的相反颜色代码