首页 > 解决方案 > 如何在 CSS 函数中读取样式的值

问题描述

我通过插入这样的东西在Javascript中创建了几个div

'<div style="background-color:' + bgColor + '</div>'

现在我想color根据背景的亮度自动将文本设置为黑色或白色。

我看到 2 个选项 - 全部由 Javascript 驱动或仅在 CSS 中驱动。我更喜欢 CSS 选项,但是,不知道如何读取 CSS 函数的背景颜色,例如

@function set-color($color) {
  @if (lightness($color) > 40) {
    @return #000;
  }
  @else {
    @return #FFF;
  }
}

我怎样才能获取背景颜色来做这样的事情

div { color: set-color(???); }

怎么样mix-blend-mode

标签: javascripthtmlcss

解决方案


关于如何根据背景颜色在黑色和白色之间选择文本颜色的问题提出了几个想法。

大多数都在评论中以一种或另一种方式回答。将思路一一采纳:

我们可以使用 CSS mix-blend-mode - 不。没有一种设置可以确保文本在所有可能的背景上都可读。

我们可以使用 CSS(首选方法)吗 - 不幸的是,不可以,因为需要文本颜色依赖于背景颜色的 div 是由 JS 在运行时创建的。

我们可以使用 JS - 是的,因为 div 是由 JS 创建的并且设置了它的背景颜色,那么它也可以设置它的颜色。

JS 字符串与问题中给出的一样,并添加了颜色设置:

'<div style="background-color:' + bgColor + '; 颜色: ' + textBlackOrWhite(bgColor) + ';"'

这是一个定义函数的片段。该片段还允许您选择背景颜色,然后设置一种颜色,该颜色(大致)取决于背景的“亮度”。请参阅此处引用的 SO 问题以进行进一步讨论,因为人类颜色感知是一个困难的话题。

//from https://stackoverflow.com/questions/5623838/rgb-to-hex-and-hex-to-rgb
function textBlackOrWhite(hex) {
  // Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF")
  var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
  hex = hex.replace(shorthandRegex, function(m, r, g, b) {
    return r + r + g + g + b + b;
  });

  let result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);//also checks we have a well-formed hex number
  
//from https://stackoverflow.com/questions/596216 the answer by @FranciPenov which gives an approximation: (R+R+G+G+G+B)/6 
  let itsbright = function () { return ((2*parseInt(result[1], 16) + 3*parseInt(result[2], 16) + parseInt(result[3], 16))/6)>127; }
  return result ? (itsbright()) ? '#000000' : '#ffffff' : '#000000';//falls back onto black if bgColor was not a well-formed 3 or 6 digit hex color
}
<div id="div" style="font-family: monospace; box-sizing: border-box; margin: 0; padding: 40px 0; width: 100px; height: 100px; border-style: solid; border-radius: 50%; background-color: black; color: white;text-align:center;">#ffffff</div>
Click to choose background color: <input id="input" placeholder='#00000' type='color' value='#000000'/>
<button onclick="let d = document.getElementById('div'); let i = document.getElementById('input'); d.innerHTML = i.value; d.style.backgroundColor = i.value; d.style.color = textBlackOrWhite(i.value);">Submit</button>


推荐阅读