自动更改文本颜色以确保可读性

编程入门 行业动态 更新时间:2024-10-27 14:26:53
本文介绍了自动更改文本颜色以确保可读性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

用户可以通过接受 RGB 十六进制表示法的文本框设置按钮的背景颜色:ff00ff、ccaa22 等,所以我需要设置文本颜色到对面.不确定术语(相反的颜色),但想法是确保可读性.

Users can set the background-color of a button through a textbox that accept RGB hexadecimal notation: ff00ff, ccaa22, etc. So I need to set the text color to the opposite. Not sure about the terminology (opposite color) but the idea is assure readability.

推荐答案

您可以反转背景色并将其用作前景色.以下算法产生的结果与 Photoshop 中的图像 > 调整 > 反转"颜色命令相同:

You can invert the background color and use it as foreground color. The following algorithm produces results identical to the "Image > Adjustments > Invert" color command in Photoshop:

function invertColor(hexTripletColor) { var color = hexTripletColor; color = color.substring(1); // remove # color = parseInt(color, 16); // convert to integer color = 0xFFFFFF ^ color; // invert three bytes color = color.toString(16); // convert to hex color = ("000000" + color).slice(-6); // pad with leading zeros color = "#" + color; // prepend # return color; } /* * Demonstration */ function randomColor() { var color; color = Math.floor(Math.random() * 0x1000000); // integer between 0x0 and 0xFFFFFF color = color.toString(16); // convert to hex color = ("000000" + color).slice(-6); // pad with leading zeros color = "#" + color; // prepend # return color; } $(function() { $(".demolist li").each(function() { var c1 = randomColor(); var c2 = invertColor(c1); $(this).text(c1 + " " + c2).css({ "color": c1, "background-color": c2 }); }); });

body { font: bold medium monospace; } .demolist { margin: 0; padding: 0; list-style-type: none; overflow: hidden; } .demolist li { float: left; width: 5em; height: 5em; text-align: center; }

<ul class="demolist"> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> </ul> <script src="ajax.googleapis/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

请注意,这不是防弹解决方案.接近 50% 亮度和/或饱和度的颜色不会产生足够的对比度.

Note that this is not a bullet-proof solution. Colors that are close to 50% brightness and/or saturation will not produce sufficient contrast.

jsFiddle 演示

更多推荐

自动更改文本颜色以确保可读性

本文发布于:2023-11-06 01:52:04,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1562420.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:可读性   文本   颜色   以确保

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!