1

Fontdeck 不提供自己托管文件的选项,不幸的是,它返回的 CSS 具有针对不同字体变体的不同字体系列:

@font-face {
    font-family: 'Apercu Pro Light';
    src: ...;
    font-weight: 200;
    font-style: normal;
}

@font-face {
    font-family: 'Apercu Pro Bold Italic';
    src:...;
    font-weight: bold;
    font-style: italic;
}

@font-face {
    font-family: 'Apercu Pro Regular';
    src: null;
    font-weight: normal;
    font-style: normal;
}

这非常不方便,特别是考虑到他们已经知道正确的重量和风格。我可以解决这个问题并仍然在我的 CSS 中使用Apercufont-family并让浏览器找出要使用的字体吗?

4

1 回答 1

1

由于 Fontdeck 建议使用webfontloader来加载字体,我们可以监听它的事件并在<style>它可用时重写它附加的内联标签:

(function () {
  'use strict';

  var hasRewrittenRules = false;

  /**
   * Fontdeck returns different font-family for each font variation.
   * We will rewrite inline <style> it creates to have one font-family.
   */
  function rewriteFontFaceRules() {
    if (hasRewrittenRules) {
      return;
    }

    var key,
        sheet,
        index,
        rule,
        fontFamily;

    for (key in document.styleSheets) {
      sheet = document.styleSheets[key];
      if (!sheet.ownerNode || sheet.ownerNode.tagName !== 'STYLE') {
        continue;
      }

      for (index in sheet.rules) {
        rule = sheet.rules[index];
        if (!(rule instanceof window.CSSFontFaceRule)) {
          continue;
        }

        fontFamily = rule.style.fontFamily;

        // CHANGE REWRITING RULES HERE:

        if (fontFamily && fontFamily.indexOf('Apercu') > -1 && fontFamily !== 'Apercu') {
          rule.style.fontFamily = 'Apercu';
          hasRewrittenRules = true;
        }
      }
    }
  }

  window.WebFontConfig = {
    fontdeck: { id: /* YOUR FONT ID */ },
    fontactive: rewriteFontFaceRules,
    active: rewriteFontFaceRules
  };

  var wf = document.createElement('script');
  wf.src = ('https:' === document.location.protocol ? 'https' : 'http') +
  '://ajax.googleapis.com/ajax/libs/webfont/1/webfont.js';
  wf.type = 'text/javascript';
  wf.async = 'true';
  var s = document.getElementsByTagName('script')[0];
  s.parentNode.insertBefore(wf, s);
})();
于 2014-11-17T15:31:49.290 回答