如何解决Fontdeck为一种字体提供不同的字体系列?

时间:2014-11-17 15:31:49

标签: css font-face font-family webfont-loader

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中使用Apercu作为font-family并让浏览器确定要使用哪种字体?

1 个答案:

答案 0 :(得分: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);
})();