javascript - 如何根据动态变化的背景颜色动态改变文字颜色

标签 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 上的备用主页。我有一个动态背景,但有些颜色与我的白色文本形成鲜明对比。

最佳答案

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

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) {
      // http://stackoverflow.com/a/3943023/112731
      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>

取自How can I generate the opposite color according to current color?的反色代码

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

关于javascript - 如何根据动态变化的背景颜色动态改变文字颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55772303/

相关文章:

javascript - 如何按顺序执行功能 : 1. 放大 -> 2. 旋转 360 度 -> 3. 调整到放大前的大小 -> 4. 更改颜色(切换)

javascript - 如何将多个 html 表格导出到 excel?

javascript - 将 div 置于图像顶部

javascript - 控制 d3 sunburst 图中分隔线的宽度

javascript - 服务器端的 ASP.NET 确认对话框

html - 在 HTML 中渲染人体

javascript - 如何 jQuery - 添加按钮插入最多 10 个新输入

javascript - 在 Bootstrap 模式中使用背景 :"static"时显示无覆盖(透明背景)

Javascript 将行添加到 Javascript 生成的表中

html - 如何使边框在一部分透明?