我有一个按预期工作的随机颜色生成器,但是我想在生成的任何颜色之上使用白色文本,当然,当生成的颜色很浅时,这不好,因为对比度使文本不可读。
const generateColour = () => '#' + Math.random().toString(16).slice(-6);
我想知道是否有任何方法可以改变我当前的代码,以意味着我只接收足够暗的颜色以达到可访问的对比度?
使用 HSL,直接在 CSS 中使用或转换为 RGB。选择 S 和 L 固定范围,这样颜色就不会太浅。
let count = 10;
while(count--) {
document.body.insertAdjacentHTML('beforeend', `<div class="color-chip" style="background-color:hsl(${Math.random()*360|0}deg,${Math.random()*30|0+60}%,${Math.random()*35|0+20}%)">TEXT</div>`);
}
.color-chip{
display:inline-block;
float:left;
height:30px;
width:50px;
margin:5px;
color:white;
line-height:30px;
text-align:center;
font-weight:bold;
}