如何在js中列出css中的@font-face

how to list the @font-face from css in js

我在 css 规则 @font-face 中有字体声明,我试图用 js

列出它们

类似的东西:

css :
@font-face {font-family: font-name-1; src: ...}
@font-face {font-family: font-name-2; src: ...}
@font-face {font-family: font-name-3; src: ...}

js :
let font_list = list_my_fonts(); // ["font-name-1", "font-name-2", "font-name-3"];

我试过了:

let font_list = getComputedStyle(document.documentElement).getPropertyValue('font-face');
// empty string

或:

let font_list = Array.from(document.styleSheets);
// it gives me a big array of array in which i can't find the font-face rules

但我真的对 js 一窍不通,所以我很难确切地知道该怎么做才能达到我的目标

这里有实现。它使用 Document.fonts 属性.

function list_my_fonts() {
  return Array.from(document.fonts);
}

console.log(list_my_fonts());
<link rel="preconnect" href="https://fonts.gstatic.com"> 
<link href="https://fonts.googleapis.com/css2?family=Roboto:ital,wght@1,300&display=swap" rel="stylesheet">

const font = new FontFace('myfont', 'url(myfont.woff)');

然后使用 .load 方法加载此字体,然后 return 一个 promise

font.load().then((fetchedfont)=>{
  document.fonts.add(fetchedfont)
})
.catch((error)=>console.log(error))

您可以在 https://developer.mozilla.org/en-US/docs/Web/API/FontFace/FontFace

阅读更多内容
// get all the styleSheets
const styleSheets = Array.from(document.styleSheets);

styleSheets.forEach(styleSheet => {
  const cssRules = styleSheet.cssRules;

  // all the font-faces rules
  const rulesFontFace = cssRules.filter(rule => rule.cssText.startsWith('@font-face'));

  rulesFontFace.forEach(fontFace => {
    console.log(fontFace); // CSSFontFaceRule object
  });
});

关于 CSSStyleSheet 的更多信息:https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleSheet

关于 cssRules 的更多信息:https://developer.mozilla.org/en-US/docs/Web/API/CSSKeyframesRule/cssRules

-或-

关于 CSSFontFaceRule 的更多信息:https://developer.mozilla.org/en-US/docs/Web/API/CSSFontFaceRule