首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >页面加载后动态加载google字体

页面加载后动态加载google字体
EN

Stack Overflow用户
提问于 2013-05-15 05:41:32
回答 2查看 23.3K关注 0票数 26

我希望能够让用户选择他们想要的字体来显示页面。Here是谷歌推荐你使用JavaScript的方式。

代码语言:javascript
复制
WebFontConfig = {
    google: {
        families: ['Tangerine', 'Cantarell']
    }
};

(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);
      })();

我如何修改它,以便在页面加载后可以重新获得字体?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-05-15 06:10:43

查看此github存储库中的WebFont.load命令:

https://github.com/typekit/webfontloader

你可以动态加载任何你想要的字体:

代码语言:javascript
复制
 <script src="http://ajax.googleapis.com/ajax/libs/webfont/1/webfont.js"></script> 
  <script> 
        WebFont.load({
                    google: { 
                           families: ['Droid Sans', 'Droid Serif'] 
                     } 
         }); 
   </script>
票数 36
EN

Stack Overflow用户

发布于 2021-01-27 18:22:04

或者,如果您不需要第三方库:

代码语言:javascript
复制
function addStylesheetURL(url) {
  var link = document.createElement('link');
  link.rel = 'stylesheet';
  link.href = url;
  document.getElementsByTagName('head')[0].appendChild(link);
}

// Load Tangerine & Cantarell
addStylesheetURL('https://fonts.googleapis.com/css2?family=Cantarell&family=Tangerine&display=swap');
代码语言:javascript
复制
    h1 {
      font-family: 'Cantarell', sans-serif;
    }
    p {
      font-family: 'Tangerine', cursive;
      font-size: 30px;
    }
代码语言:javascript
复制
<!DOCTYPE html>
<html>
  <head>
    <title>Dynamically load google fonts after page has loaded</title>
    <link rel="preconnect" href="https://fonts.gstatic.com">
  </head>
  <body>
    <h1>Dynamically load google fonts after page has loaded</h1>
    <p>Some text.</p>
  </body>
</html>

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/16553326

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档