我知道您可以通过 window.getComputedStyle()
获取 font-family
值,但这并不总是浏览器用来呈现的字体。例如,如果给定文本包含字体系列不包含的(多语言)文本,则浏览器会使用系统字体部分呈现文本。
如果您查看 Chrome 或 Firefox 中的内置 Web 开发人员工具,它们都有一个小区域可以显示(Chrome 上的 Rendered Fonts
Pane 或 Fonts
tab on Firefox) 使用的确切字体。对于 Firefox,我猜 this code被使用了,它似乎在调用内部 API。
我正在寻找任何符合 DOM(或特定于 vendor )的方式来从 JavaScript 领域或其他方面获取准确的字体。如果这意味着编写浏览器扩展/附加组件来提供 API/注入(inject)信息/任何页面内代码访问的内容,那是最坏的情况,但可以接受。
您可以使用 hack:主要思想是将内联元素的大小与某些给定字体进行比较。一个应该使用完整的字体系列值,另一个应该只使用一个字体系列。这是 a proof of concept效果很好。
// Look at the fiddle for full working code
function createFontTester(fontFamily) {
var container = document.createElement('div');
var tester = document.createElement('div');
container.style.position = 'absolute';
container.style.overflow = 'auto';
container.style.visibility = 'hidden';
tester.style.fontFamily = fontFamily;
tester.style.display = 'inline';
tester.style.visibility = 'hidden';
// The size should be big enough to make a visual difference
tester.style.fontSize = '100px';
// Reset and prevent line breaks
tester.style.fontWeight = 'normal';
tester.style.fontStyle = 'normal';
tester.style.letterSpacing = 'normal';
tester.style.lineHeight = 'normal';
tester.style.whiteSpace = 'nowrap';
document.body.appendChild(container);
container.appendChild(tester);
return tester;
}
请注意,有些字体非常相似,以至于大多数字符占用相同的空间。以 Helvetica 和 Arial 为例:字符宽度基本相同,高度略有不同,所以我使用了大字体。
这种方法可能不是万无一失的,但它适用于我能想到的所有字体系列。
更新:我做了this little library在 Github 上处理更多用例。