bea*_*tak 5 javascript firefox fonts google-chrome browser-extension
我知道你可以获得font-family
值,window.getComputedStyle()
但这并不总是浏览器用来呈现的字体.例如,如果给定的文本包含(多语言)文本的字体族不携带,浏览器呈现部分地与系统字体的文本.
如果你看一看内置的web开发工具,无论是在Chrome或Firefox,他们都有一个小区域,以显示(Rendered Fonts
在Chrome窗格或Fonts
选项卡上的Firefox浏览器)所使用的确切的字体.对于Firefox,我想这个代码是用的,它似乎是在调用内部API.
我正在寻找任何符合DOM(或特定于供应商)的方式来从JavaScript土地获取确切的字体.如果这意味着编写浏览器扩展/附加组件以提供API /注入信息/任何内页代码访问,这是最糟糕的情况,但可以接受.
您可以使用 hack:主要思想是将内联元素的大小与某些给定字体进行比较。一个应该使用完整的字体系列值,另一个应该使用单个字体系列。这是一个效果很好的概念证明。
// 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;
}
Run Code Online (Sandbox Code Playgroud)
请注意,某些字体非常相似,以至于大多数字符占用相同的空间。以 Helvetica 和 Arial 为例:字符宽度基本相同,高度略有不同,因此我使用了较大的字体大小。
这种方法可能不是万无一失的,但它适用于我能想到的每个字体系列。
更新:我在 Github 上制作了这个小库,它可以处理更多用例。
归档时间: |
|
查看次数: |
654 次 |
最近记录: |