You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用JavaScript检测浏览器实际选用的指定字体?

检测浏览器实际使用的字体方案

window.getComputedStyle只会返回CSS中声明的字体列表,无法直接获取浏览器实际渲染时选用的字体。要解决这个问题,可以利用不同字体对同一文本的渲染尺寸差异来判断,具体实现如下:

实现思路

创建两个隐藏的测试元素:

  • 第一个元素使用你要检测的目标字体 + 兜底字体(比如sans-serif)
  • 第二个元素仅使用兜底字体
    通过对比两者的渲染宽度(或高度),如果尺寸不同,说明目标字体存在且被浏览器实际选用。

代码示例

function detectActualFont(targetFont, fallbackFont = 'sans-serif') {
  // 选用宽度差异明显的字符作为测试文本,提升检测准确性
  const testText = "mmmmmm";
  // 创建两个用于对比的span元素
  const span1 = document.createElement('span');
  const span2 = document.createElement('span');
  
  // 设置统一的基础样式,排除字体外的其他干扰因素
  const baseStyle = `
    position: absolute;
    left: -9999px;
    top: -9999px;
    font-size: 100px;
    padding: 0;
    margin: 0;
    border: none;
    background: none;
  `;
  
  span1.style.cssText = baseStyle + `font-family: ${targetFont}, ${fallbackFont};`;
  span2.style.cssText = baseStyle + `font-family: ${fallbackFont};`;
  
  span1.textContent = testText;
  span2.textContent = testText;
  
  // 插入DOM触发渲染
  document.body.appendChild(span1);
  document.body.appendChild(span2);
  
  // 获取渲染后的宽度值
  const width1 = span1.offsetWidth;
  const width2 = span2.offsetWidth;
  
  // 清理临时元素
  document.body.removeChild(span1);
  document.body.removeChild(span2);
  
  // 宽度不同则说明目标字体被实际启用
  return width1 !== width2;
}

// 针对你的场景检测Liberation Sans是否被使用
const isLiberationSansUsed = detectActualFont("'Liberation Sans'");
console.log('是否实际使用Liberation Sans:', isLiberationSansUsed);

注意事项

  • 优先选择宽度差异大的字符作为测试文本(比如小写m、w),避免用i、l这类窄字符,减少误判概率
  • 确保两个测试元素的样式完全一致(字体大小、边距等),排除非字体因素对尺寸的影响
  • 如果目标字体和兜底字体渲染尺寸极其接近,可更换测试文本或调大字体大小优化检测精度

内容的提问来源于stack exchange,提问作者Skilo83

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 14:20:04