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

瀏覽器相容性

另見