根据动态变化的背景颜色,如何动态更改文本颜色

6
我正在建立一个新网站,需要根据不断变化的背景颜色改变文本颜色以保持对比度。我已经搜索了很多网页,但没有一种方法不涉及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上的备用首页。我有一个动态背景,但是有些颜色与我的白色文本对比不好。

为什么不像字幕一样添加一个轻微的文字阴影呢? - SuperDJ
1
谁在调用 isDarkColor - brk
1个回答

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

function invertColor(hex, bw) {
    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.');
    }
    var r = parseInt(hex.slice(0, 2), 16),
      g = parseInt(hex.slice(2, 4), 16),
      b = parseInt(hex.slice(4, 6), 16);
    if (bw) {
      // https://dev59.com/sW865IYBdhLWcg3wLrhE#3943023
      return (r * 0.299 + g * 0.587 + b * 0.114) > 186 ?
        '#000000' :
        '#FFFFFF';
    }
    // invert color components
    r = (255 - r).toString(16);
    g = (255 - g).toString(16);
    b = (255 - b).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,true);
    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>

取自如何根据当前颜色生成相反的颜色?的对立颜色代码。

在invertColor()中添加了一个额外的参数bw,如果将bw设置为true,则文本颜色将为黑色,如果背景亮度较高,则反之亦然。


感谢您提供如此出色的代码!不过,我想知道是否有可能只保持文本为黑色或白色... - Jonathan Lee
太棒了!非常感谢!我最后要解决的问题是是否可以控制颜色变化的速度,即每3000毫秒平滑地改变颜色... - Jonathan Lee

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接