【问题标题】:How google fonts loads fonts dynamically谷歌字体如何动态加载字体
【发布时间】:2020-05-18 20:57:50
【问题描述】:

在 Google 字体网站 (https://fonts.google.com/) 中,它们会在滚动时动态添加 <li> 元素。那些<li> 元素具有<a> 标签和href 属性(截图如下),其url 值指向字体页面。然后在<li> 的更深处有一个<gf-content-editable> 元素,它将font-family CSS 值设置为实际的字体系列。

有人能解释一下他们是怎么做到的吗?正在寻找一种动态加载字体的方法,但 CSS Font Loading API 仍处于试验阶段。

感谢您提供任何见解。

【问题讨论】:

  • 由于这是一种内联样式,它很可能是使用 JavaScript 设置的。因此,一个数据对象指示要显示的所有字体,然后迭代对象中的每种字体以为每个字体系列创建
  • 元素。通过这种方式,他们可以自动创建 href 标签并在每张卡片上设置字体样式。如果你愿意,我可以为你复制一个简单的例子。
  • 会很有趣,因为我想到的唯一其他选择是为每个新字体添加到 中。欢迎您提供答案:)
  • 刚刚发布了答案
  • 标签: javascript webfonts


    【解决方案1】:

    执行此操作的一种方法是使用来自数据库或任何其他来源的数据创建一个对象,并对其进行迭代以动态创建卡片。一个简单的例子可能是:

    const data = [
        {
            fontFamily: 'Open Sans',
            href: 'Open+Sans+Condensed',
            // Other attributes
        },
        // Other fonts
    ]
    
    for(const font of data) {
    
        let li, gridItemTemplate, gfFontPreview, a, section, gfContentEditable /*other elements*/;
        li = document.createElement('li')
        li.setAttribute('class', 'grid-list-tile is-in-last-column');
        // Other attributes
    
        gridItemTemplate = document.createElement('grid-item-template');
    
        gfFontPreview = document.createElement('gf-font-preview')
        gfFontPreview.setAttribute('class', 'grid-list-font-preview');
        // Other attributes
    
        a = document.createElement('a')
        a.setAttribute('class', 'https://fonts.google.com/specimen' + font.href);
        // Other attributes
    
        section = document.createElement('section');
        section.setAttribute('class', 'font-preview-card-static ...');
    
        gfContentEditable = document.createElement('gf-content-editable')
        gfContentEditable.setAttribute('class', 'preview-text-font-card static-font...')
        gfContentEditable.setAttribute('style', `font-size: 40px; line-height: 1.10909; font-family: "${font.fontFamily} script=latin rev=1"; weight: 300; font-style: normal;`);
        gfContentEditable.innerText = 'Almost before we knew it, we had left the ground.';
    
        document
            .body
            .appendChild(li)
            .appendChild(gridItemTemplate)
            .appendChild(gfFontPreview)
            .appendChild(a)
            .appendChild(section)
            .appendChild(gfContentEditable);
    
    }
    

    这是一种非常冗长的写法。如果你真的想为你的网站创建这个函数,你可以将很多代码抽象成单独的函数,或者使用模板引擎或库来实现这一点。我只是分享这个来展示我如何利用我从问题中获得的信息来实现这一目标。

    【讨论】:

    • 谢谢,稍后再调查
    猜你喜欢
    相关资源
    最近更新 更多
    热门标签