CSS,如果找不到字体并使用替代字体,则自动更改大小等样式

CSS, automatically change styles like size, etc. if font is not found and alternative is used

如果无法加载或找不到我正在使用的字体,将使用备用字体。如果是这样,我需要更改一些其他样式,例如 font-weightletter-spacingfont-size

例如:

div {
      font-family:"Lemon",sans-serif;
    }

这里的 Lemon 是一种非常粗的字体,所以我设计这种字体的方式可能不适合替代字体。那么,如果无法加载第一个指定的字体,我该如何相应地更改替代字体的样式?

使用纯CSS,你不能。一种选择是使用 javascript 到 detect if a font is installed,然后相应地调整您的样式。

类似于:

$(document).ready(function () {
  font.setup(); // run setup when the DOM is ready

  if (!font.isInstalled("Lemon")) {
    document.getElementById("example-div").style.fontWeight = "900";
  }
});

这利用了 font.js,它必须包含在您的页面中。

警告:此方法应该能够检测是否加载了任何非等宽字体。

看来单独使用 CSS 无法感知实际使用的字体。从@Eddie Reeder 回答中突出显示的 font.js 和 github.com/philoye/fontunstack/tree/master 中获取想法,我们可以根据另一种字体来衡量所需的字体。我选择了一种等宽字体进行测试,并选择了一串窄字符 (i) 作为最有可能与所需字体不同的字体。 像这样的代码(我故意把它拼写出来以弄清楚发生了什么)可能放在头部或正文的开头。它当然可以放在一个函数中,在开始时调用 and/or 一旦所需的脚本被设置 and/or 来删除它的测试 div 来设置 CSS 变量,如果这样的话比有两个单独的 css 样式文件更有意义。

<div id="maybeOurFont" style="font-family: Lemon, monospace; font-size: 100px; position: absolute; left: -9999px; top:0;">iiiiiiiiiiiiiiiiiiii</div>
<div id="testFont" style="font-family: monospace; font-size: 100px; position: absolute; left: -9999px; top:0;">iiiiiiiiiiiiiiiiiiii</div>
<script>
  const pathToLemonStyle = "lemonstyle.css"; //replace with your path
  const pathToNoLemonstyle = "nolemonstyle.css"; // ditto
  const lemonLength = document.getElementById("maybeOurFont").offsetWidth;
  const monoLength = document.getElementById("testFont").offsetWidth;
  let useThisStyle = pathToLemonStyle;
  if ( lemonLength == monoLength ) {
    useThisStyle= pathToNoLemonstyle;
  }
  document.head.append('<style src="' + useThisStyle + '"></style>');
</script>