我知道你可以通过font-family
得到window.getComputedStyle()
值,但这并不总是浏览器用来呈现的字体。例如,如果给定文本包含字体系列不携带的(多语言)文本,则浏览器会使用系统字体部分呈现文本。
如果你看一下内置的网页开发者工具,无论是在Chrome还是Firefox中,它们都有一小块区域可供展示(Chrome上的Rendered Fonts
窗格或Firefox上的Fonts
标签使用的确切字体。对于Firefox,我猜使用了this code,它似乎在调用内部API。
我正在寻找任何符合DOM标准(或特定于供应商)的方式来获取JavaScript领域的确切字体。如果这意味着编写浏览器扩展/附加组件以提供API /注入信息/任何内页代码访问,这是最糟糕的情况,但可以接受。
答案 0 :(得分:0)
您可以使用hack:主要思想是将内联元素的大小与某些给定字体进行比较。一个应该使用完整的font-family值,另一个应该只使用一个font-family。这是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为例:字符宽度大致相同,高度略有不同,所以我使用了大字体。
这种方法可能不是防弹的,但它适用于我能想到的每个字体系列。
更新:我在Github上制作了this little library来处理更多用例。