PHP前端开发

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

百变鹏仔 4周前 (09-22) #HTML
文章标签 亮度

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

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) ? &#39;black&#39; : &#39;white&#39;;     // for background  var b = &#39;rgb(&#39; + rgb[0] + &#39;,&#39; + rgb[1] + &#39;,&#39; + rgb[2] + &#39;)&#39;;  $(&#39;#box&#39;).css(&#39;color&#39;, f);  $(&#39;#box&#39;).css(&#39;background-color&#39;, 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;}