CSSFontPaletteValuesRule:overrideColors 属性

Baseline 已广泛支持

此功能已成熟,可跨多种设备和浏览器版本使用。自 ⁨2022 年 11 月⁩起,所有浏览器均支持此功能。

CSSFontPaletteValuesRule 接口的只读 overrideColors 属性是一个字符串,其中包含要替换的颜色索引和颜色对列表。它的格式与相应的 override-colors 描述符相同。

一个包含逗号分隔的颜色索引和颜色对列表的字符串

示例

读取覆盖的颜色

此示例首先定义了几个 at-rules,其中包含两个 @font-palette-values。MDN 的 实时示例 基础结构会将示例中的所有 CSS 块合并到一个 id 为 css-output 的内联样式中,因此我们首先使用 document.getElementById() 来查找该样式表。

HTML

html
<div class="hat">
  <div class="emoji colored-hat">🎩</div>
</div>
<button>Toggle color</button>
<pre id="log"></pre>

CSS

css
@font-face {
  font-family: "Noto Color Emoji";
  font-style: normal;
  font-weight: normal;
  src: url("https://fonts.gstatic.com/l/font?kit=Yq6P-KqIXTD0t4D9z1ESnKM3-HpFabts6diywYkdG3gjD0U&skey=a373f7129eaba270&v=v24")
    format("woff2");
}

.emoji {
  font-family: "Noto Color Emoji", emoji;
  font-size: 3rem;
}

@font-palette-values --blue {
  font-family: "Noto Color Emoji";
  override-colors:
    3 rgb(1 28 193),
    4 rgb(60 124 230);
}

@font-palette-values --green {
  font-family: "Noto Color Emoji";
  override-colors:
    3 rgb(28 193 1),
    4 rgb(34 230 1);
}

.colored-hat {
  font-palette: --blue;
}

JavaScript

js
const log = document.getElementById("log");
const button = document.querySelector("button");
const hat = document.querySelector(".colored-hat");
const rules = document.getElementById("css-output").sheet.cssRules;
const greenFontPaletteValuesRule = rules[3];
const blueFontPaletteValuesRule = rules[2];
log.textContent = `Overridden colors: ${blueFontPaletteValuesRule.overrideColors}`;

button.addEventListener("click", (event) => {
  if (hat.style.fontPalette !== "--green") {
    hat.style.fontPalette = "--green";
    log.textContent = `Overridden colors: ${greenFontPaletteValuesRule.overrideColors}`;
  } else {
    hat.style.fontPalette = "--blue";
    log.textContent = `Overridden colors: ${blueFontPaletteValuesRule.overrideColors}`;
  }
});

结果

规范

规范
CSS 字体模块第 4 级
# dom-cssfontpalettevaluesrule-overridecolors

浏览器兼容性

另见