我正在开发自定义字体功能,用户可以上传 .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/