【问题标题】:Load only specific fonts from Google API仅从 Google API 加载特定字体
【发布时间】:2016-01-07 12:29:53
【问题描述】:

我成功设置了一个带有从 Google API 加载的字体的选择框。更改选择框时,我的 textarea 也会更改字体。

只有一件事我想不通。如何仅从 API 加载特定字体,而不是包含 700 多种字体的完整列表?!

我在文档中找不到设置要加载的字体的任何地方。

我拥有的是这样的:

<head>这个代码里面有我想要的6种字体:

 <script>
   WebFontConfig = {
    google: { families: [ 'Cookie', 'Dekko', 'Ruge+Boogie', 'Great+vibes', 'Cabin', 'Open+Sans' ] }
  };
  (function() {
    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);
  })();
    </script>

在我的&lt;body&gt;

 function SetFonts(fonts) {
    for (var i = 0; i < fonts.items.length; i++) {      
      $('.styleFont').append($("<option></option>").attr("value", fonts.items[i].family).text(fonts.items[i].family));
    }    
  }
  var script = document.createElement('script');
  script.src = 'https://www.googleapis.com/webfonts/v1/webfonts?key=****&callback=SetFonts';
  document.body.appendChild(script);

  $(".styleFont").change(function () {
    var id =$('.styleFont option' + ':selected').text();    
    $(".custom-text").css('font-family',id);
  });

【问题讨论】:

    标签: javascript jquery fonts google-api


    【解决方案1】:

    你的意思是这样的吗?

    WebFontConfig = {
      google: { families: [ 'Cookie', 'Dekko', 'Ruge+Boogie', 'Great+vibes', 'Cabin', 'Open+Sans' ] }
    };
    
    function SetFonts(fonts) {
      var loadedFonts = [];
      for (var i = 0; i < fonts.items.length; i++) {
        if ((WebFontConfig.google.families.indexOf(fonts.items[i].family) > -1) &&
            (loadedFonts.indexOf(fonts.items[i].family) === -1)) {
          $('.styleFont').append($("<option></option>").attr("value", fonts.items[i].family).text(fonts.items[i].family));
          loadedFonts.push(fonts.items[i].family);
        }
      }
    }
    

    【讨论】:

    • 一件小事...这会导致选择框被字体填充两次。所以每种字体都列出了两次
    • 这似乎很奇怪,我刚刚在我原来的帖子中注意到,我缺少一个花括号来开始 if 声明,你明白了吗?如果这不是问题,看看编辑是否有帮助......
    • 我看到了缺少的括号,这不是问题所在。上面的编辑会导致错误提示 fonts is undefined...
    猜你喜欢
    • 2011-06-13
    • 2014-10-20
    • 1970-01-01
    • 2018-11-22
    • 1970-01-01
    • 2018-11-18
    • 1970-01-01
    • 1970-01-01
    • 2014-01-18
    相关资源
    最近更新 更多