Home > Web Front-end > HTML Tutorial > In HTML, change text color based on brightness of covered background area?

In HTML, change text color based on brightness of covered background area?

PHPz
Release: 2023-08-28 13:29:02
forward
652 people have browsed it

In HTML, change text color based on brightness of covered background area?

You can use the following code snippet to change the text color based on the average brightness of the pixels covered by its parent background color.

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>
Copy after login

The following is CSS -

#box {
   width: 300px;
  height: 300px;
}
Copy after login

The above is the detailed content of In HTML, change text color based on brightness of covered background area?. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template