当时忘记记录了,现在在记录一下,结合上篇文章换色后,如果选择了全黑或者全白字体会看不清什么的,在app.vue里的methods写下这个方法,注意最底下的this.color1是上篇文章里面定义的,可以换成自己想要的色彩,,,v2
chooseTextColor(bgColor) {
// 计算颜色的亮度
const brightness = (red, green, blue) => {
const a = [red, green, blue].map((v) => {
v /= 255;
return v <= 0.03928 ? v / 12.92 : Math.pow((v + 0.055) / 1.055, 2.4);
});
return a[0] * 0.2126 + a[1] * 0.7152 + a[2] * 0.0722;
};
// 将十六进制颜色转换为RGB
const hexToRgb = (hex) => {
const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
return result
? {
r: parseInt(result[1], 16),
g: parseInt(result[2], 16),
b: parseInt(result[3], 16),
}
: null;
};
const rgb = hexToRgb(bgColor);
const lightness = brightness(rgb.r, rgb.g, rgb.b);
// 根据亮度决定字体颜色
this.colorsize1 = lightness>0.29?"Black":( lightness<0.13?"White":this.color1)
},
然后在watch监听里加入这行
watch: {
"$store.state.conentColor": {
handler(val, oldval) {
this.color1 = val;
//加入这行就行了,其他行内容在上篇文章都有
this.chooseTextColor(val);
},
immediate: true,
},
},
然后再div上进行动态绑定即可,别忘了定义colorsize1
<div id="app" :style="{ '--color': color1, '--colorsize': colorsize1 }">
~~~
</div>
同理上篇文章,在想用的地方直接var(--colorsize)即可。