我想根据元素的背景颜色更改元素的文本颜色.
例如,如果背景颜色更改为黑色,则将文本设为白色.如果背景颜色更改为白色,则将文本设为黑色.
虽然用户可以将背景颜色改变为他们想要的任何颜色,但它会比那更复杂.
我发现了一些关于handling it on the backend的随机文章,但没有使用javascript(或更好的,jQuery).
解决方法
首先,创建一个确定颜色是否暗的函数(
source,修改):
@H_502_12@function isDark( color ) {
var match = /rgb\((\d+).*?(\d+).*?(\d+)\)/.exec(color);
return parseFloat(match[1])
+ parseFloat(match[2])
+ parseFloat(match[3])
< 3 * 256 / 2; // r+g+b should be less than half of max (3 * 256)
}
然后,使用以下内容:
@H_502_12@$('elem').each(function() { $(this).css("color",isDark($(this).css("background-color")) ? 'white' : 'black'); });