使用方法:
$(this)[0].change_color_for_text(); // 改变文本颜色 形成对比
代码如下:
// 1. 让元素内部的字体进行颜色对比 使其更加显眼
HTMLElement.prototype.change_color_for_text=function (){
let style = window.getComputedStyle(this); // style是一个实时的 CSSStyleDeclaration 对象,当元素的样式更改时,它会自动更新本身
let this_background_color = style.backgroundColor.toString()
this.style.color = oppositeColor(this_background_color.colorHex());
}
// 1. 颜色进制转换
/*RGB颜色转换为16进制 支持rgb和rgba*/
String.prototype.colorHex = function () {
let pattern = /^rgba/;
if (pattern.test(this)) { // 说明为rgba
var values = this
.replace(/rgba?\(/, '') // 把 "rgba(" 去掉,变成 "194, 7, 15, 1)"
.replace(/\)/, '') // 把 ")" 去掉,变成 "194, 7, 15, 1"
.replace(/[\s+]/g, '') // 把空格去掉,变成 "194,7,15,1"
.split(',') // 变成数组 [194,7,15,1]
var a = parseFloat(values[3] || 1), // values[3]是rgba中的a值,没有的话设置a为1,a可能为小数,所以用parseFloat函数
r = Math.floor(a * parseInt(values[0]) + (1 - a) * 255), // 转换为16进制
g = Math.floor(a * parseInt(values[1]) + (1 - a) * 255),
b = Math.floor(a * parseInt(values[2]) + (1 - a) * 255)
return '#' +
('0' + r.toString(16)).slice(-2) + // 转换后的16进制可能为一位,比如 7 就转换为 7 , 15 转换为 f
('0' + g.toString(16)).slice(-2) + // 当为一位的时候就在前面加个 0,
('0' + b.toString(16)).slice(-2) // 若是为两位,加 0 后就变成了三位,所以要用 slice(-2) 截取后两位
} else { // 说明为rgb
var rgb = this;
rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
function hex(x) {
return ("0" + parseInt(x).toString(16)).slice(-2);
}
return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]);
}
};
/*16进制转换为RGB颜色*/
String.prototype.colorRgb = function () {
// 16进制颜色值的正则
var reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/;
// 把颜色值变成小写
var color = this.toLowerCase();
if (reg.test(color)) {
// 如果只有三位的值,需变成六位,如:#fff => #ffffff
if (color.length === 4) {
var colorNew = "#";
for (var i = 1; i < 4; i += 1) {
colorNew += color.slice(i, i + 1).concat(color.slice(i, i + 1));
}
color = colorNew;
}
// 处理六位的颜色值,转为RGB
var colorChange = [];
for (var i = 1; i < 7; i += 2) {
colorChange.push(parseInt("0x" + color.slice(i, i + 2)));
}
return "RGB(" + colorChange.join(",") + ")";
} else {
return color;
}
};
// 2. 计算反色, ilighten - 减弱对比度(-1 ~ -15)
// 示例: oppositeColor("#000000", -4); 返回: #bbbbbb
function oppositeColor(a, ilighten = -1) {
a = a.replace('#', '');
//var max16 = 15;
var max16 = Math.floor(15 + (ilighten || 0));
if (max16 < 0 || max16 > 15) max16 = 15;
var c16, c10, b = [];
for (var i = 0; i < a.length; i++) {
c16 = parseInt(a.charAt(i), 16); // to 16进制
c10 = parseInt(max16 - c16, 10); // 10进制计算
if (c10 < 0) c10 = Math.abs(c10);
b.push(c10.toString(16)); // to 16进制
}
return '#' + b.join('');
}