我知道您可以通过font-family
获得window.getComputedStyle()
值,但这并不总是浏览器用来呈现的字体。例如,如果给定的文本包含字体系列不携带的(多语言)文本,则浏览器将部分使用系统字体呈现文本。
如果您看一下内置的web开发工具,无论是在Chrome还是Firefox中,它们都有一个小区域可显示( Chrome上的Rendered Fonts
窗格或火狐上的Fonts
选项卡)所使用的精确字体。对于火狐,我猜是使用了这段代码,它似乎在调用内部API。
我正在寻找任何符合DOM(或特定供应商)的方式,从JavaScript或其他地方获得准确的字体。如果这意味着编写浏览器扩展/加载项来提供API/inject /任何页面内代码要访问的内容,这是最坏的情况,但可以接受。
发布于 2015-09-29 13:59:04
--您可以使用黑客进行:主要思想是将内联元素的大小与某些给定的字体进行比较。一个应该使用完整的字体族值,另一个只能使用一个字体系列.这是概念的证明,它工作得很好。
// 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上创建了这个小图书馆,它处理更多的用例。
https://stackoverflow.com/questions/32854083
复制相似问题