是否可以获取元素渲染字体的文件名?
示例:
@font-face {
font-family: 'MyFont';
src: url('../../public/fonts/MyFont-Bold.woff2') format('woff2');
font-weight: bold;
font-style: normal;
}
@font-face {
font-family: 'MyFont';
src: url('../../public/fonts/MyFont-Italic.woff2') format('woff2');
font-weight: normal;
font-style: italic;
}
.my-font-bold {
font-family: 'MyFont';
font-weight: bold;
font-style: normal;
}
<p className="my-font-bold"></p>
在此示例中,我想获取元素的
../../public/fonts/MyFont-Bold.woff2
(因为它具有 font-weight 粗体和 font-family =“MyFont”,这要归功于 className“my-font-bold”)。
PS:我想这样做是为了进行字体 JEST 测试。
getComputedStyle
即可实现这一目标。
达到要求的步骤:
p
标签正在使用的字体名称。url
并返回结果,否则返回 null
。代码实现:
function getRenderedFontUrl(element) {
const fontFamily = window.getComputedStyle(element).getPropertyValue('font-family').replace(/['"]/g, '');
const cssRules = Array.from(document.styleSheets).flatMap(sheet => Array.from(sheet.cssRules));
const fontFaceRule = cssRules.find(rule => {
return rule.type === CSSRule.FONT_FACE_RULE && rule.style.getPropertyValue('font-family') === fontFamily;
});
if (fontFaceRule) {
const src = fontFaceRule.style.getPropertyValue('src');
const urlRegex = /url\((['"]?)(.*?)\1\)/g;
const match = urlRegex.exec(src);
return match ? match[2] : null;
}
return null;
}
// Usage example
const paragraphElement = document.querySelector('p');
const fontUrl = getRenderedFontUrl(paragraphElement);
console.log(fontUrl); // "../../public/fonts/MyFont.woff2"
@font-face {
font-family: 'MyFont';
src: url('../../public/fonts/MyFont.woff2') format('woff2');
font-weight: 300;
font-style: normal;
}
p {
font-family: 'MyFont';
}
<p style="font-family: 'MyFont'; font-weight: bold;">