思涯谷

  • 首页
  • 探索
  • 标签
  • 关于
思涯谷 ©2025
京ICP备2022030312号GitHub User's stars

根据背景获取文字颜色

G18: Ensuring that a contrast ratio of at least 4.5:1 exists between text (and images of text) and background behind the text

...
标签:笔记前端JavaScript教程
点赞(0)
返回顶部

相关内容

  • 单页应用(SPA)和多页应用(MPA)
  • 面试笔记
  • VSCode笔记
  • 后真相时代
  • 《现实不似你所见》摘录
01-10

留言

根据Web无障碍设计标准,文字颜色和背景需要满足一定的对比度:

WCAG G18: Ensuring that a contrast ratio of at least 4.5:1 exists between text (and images of text) and background behind the text

/**
 * 获取文字对比色
 * @param backgroundColor rgb(0,0,0)
 * @returns rgb(255,255,255) | rgb(0,0,0)
 */
export function getContrastColor(backgroundColor: string) {
  const rgb = backgroundColor.match(/\d+/g)!.map(Number)
  const [r, g, b] = rgb.map((c) => {
    const r = c / 255.0
    if (r <= 0.03928) {
      return r / 12.92
    } else {
      return Math.pow((r + 0.055) / 1.055, 2.4)
    }
  })

  return 0.2126 * r + 0.7152 * g + 0.0722 * b > 0.179
    ? "rgb(0,0,0)"
    : "rgb(255,255,255)"
}

依背景色決定文字顏色的正確姿勢 - W3C 標準