在 HTML 中,如何根据覆盖背景区域的亮度更改文本颜色?

htmlweb developmentfront end technology更新于 2025/8/18 15:08:17

可以使用以下代码片段,根据父元素背景颜色覆盖像素的平均亮度更改文本颜色。

var rgb = [255, 0, 0];
setInterval(display, 1000);
function display() {
   rgb[0] = Math.round(Math.random() * 255);
   rgb[1] = Math.round(Math.random() * 255);
   rgb[2] = Math.round(Math.random() * 255);
   
   var d = Math.round(((parseInt(rgb[0]) * 299) + (parseInt(rgb[1]) * 587) +
      (parseInt(rgb[2]) * 114)) / 1000);
   // for foregound
   var f = (d> 125) ? 'black' : 'white';
   
  // for background
  var b = 'rgb(' + rgb[0] + ',' + rgb[1] + ',' + rgb[2] + ')';
  $('#box').css('color', f);
  $('#box').css('background-color', b);
}
<scriptsrc = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div id = "box"> Demo</div>

以下是 CSS −

#box {
   width: 300px;
  height: 300px;
}

相关文章


有用资源