javascript - 如何在自定义字体 css 文件中查找可用的字体粗细

标签 javascript css fonts font-face custom-font

我正在开发自定义字体功能,用户可以上传 .css 文件并在我们的编辑器中使用它。为了进行显示,我需要知道文件中存在的字体粗细,以便我可以在编辑器的下拉列表中显示它们。

请建议一种最佳方法来计算自定义字体可用的字体粗细。由于用户将上传文件,因此我不会知道字体粗细。

用户输入:

/* latin */
@font-face {
  font-family: 'Poppins';
  font-style: italic;
  font-weight: 200;
  font-display: swap;
  src: url(https://fonts.gstatic.com/s/poppins/v20/pxiDyp8kv8JHgFVrJJLmv1pVF9eOYktMqg.woff2) format('woff2');
}
/* devanagari */
@font-face {
  font-family: 'Poppins';
  font-style: italic;
  font-weight: 300;
  font-display: swap;
  src: url(https://fonts.gstatic.com/s/poppins/v20/pxiDyp8kv8JHgFVrJJLm21lVFteOYktMqlap.woff2) format('woff2');
}
/* latin */
@font-face {
  font-family: 'Poppins';
  font-style: italic;
  font-weight: 400;
  font-display: swap;
  src: url(https://fonts.gstatic.com/s/poppins/v20/pxiGyp8kv8JHgFVrJJLucHtAOvWDSA.woff2) format('woff2');
}

所需数据:[200, 300, 400]

寻找 JS 解决方案。

最佳答案

感谢@herrstrietzel提供上述解决方案。

而不是创建带有 id 的样式标签,然后禁用它。我用过 CSSStyleSheet()。下面是我的代码。

/**
 * this would be css content
 * retrieved via fileReader/input
 */
let cssText = `
 /* latin */
  @font-face {
    font-family: 'Poppins';
    font-style: italic;
    font-weight: 200;
    font-display: swap;
    src: url(https://fonts.gstatic.com/s/poppins/v20/pxiDyp8kv8JHgFVrJJLmv1pVF9eOYktMqg.woff2) format('woff2');
  }

  /* latin */
  @font-face {
    font-family: 'Poppins';
    font-style: italic;
    font-weight: 400;
    font-display: swap;
    src: url(https://fonts.gstatic.com/s/poppins/v20/pxiGyp8kv8JHgFVrJJLucHtAOvWDSA.woff2) format('woff2');
  }

  /* latin-ext */
  @font-face {
    font-family: 'Agdasima';
    font-style: normal;
    font-weight: 700;
    font-display: swap;
    src: url(https://fonts.gstatic.com/s/agdasima/v2/PN_0Rfyxp2f1fUCgAPCGgCza3v3xzHMj54Y.woff2) format('woff2');
  }
`;

let cssSheet = new CSSStyleSheet()
cssSheet.replaceSync(cssText)

let rules = [...cssSheet.cssRules]
let fontProps = []
rules.forEach((rule) => {
  let type = rule.type

  // type 5 is @font-face
  if (type === 5) {
    let fontFamily = rule.style.getPropertyValue("font-family")
    let fontStyle = rule.style.getPropertyValue("font-style")
    let fontWeight = rule.style.getPropertyValue("font-weight")
    fontProps.push({
      fontFamily: fontFamily,
      fontWeight: fontWeight,
      fontStyle: fontStyle
    })
  }
})
console.log(fontProps)

关于javascript - 如何在自定义字体 css 文件中查找可用的字体粗细,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76529468/

相关文章:

html - 不使用 javascript 根据 wrap state 调整 css 样式

css - p :schedule - Wrap Text in Cells

c# - 无法在运行时显示自定义字体 - Windows Phone 8.1 MVVM - FontAwesome

javascript - 如何将超链接文件动态加载到目标/某些div?

javascript - 未捕获的语法错误 : Unexpected token { function js

javascript - javascript自调用匿名函数的使用

javascript - Bootstrap 图像弹出窗口

javascript - 即使在不同的 HTML 页面或刷新页面时,如何继续以 HTML 格式播放相同的音乐

css - 在 VueJS 中导入带有字体的 CSS 文件

css - 与 CSS 同步加载字体