在谷歌字体网站(https:/fonts.google.com。)他们加 <li>
元素的动态滚动。这些 <li>
元素有 <a>
标记 href
属性(截图如图),url值指向字体页面。然后在更深处 <li>
有 <gf-content-editable>
元素,它设置 font-family
CSS值到实际的字体系列。
谁能解释一下他们是怎么做的?寻找一种动态加载字体的方法,但是 CSS字体加载API 还是实验性的。
谢谢你的任何见解。
一种方法是使用数据库或任何其他来源的数据创建一个对象,并对其进行迭代以动态创建卡片。一个最简单的例子是这样的。
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);
}
这是个很啰嗦的写法 This is a pretty verbose way of writing this out. 如果你真的想把它作为网站的一个函数来创建,你可以把很多代码抽象成单独的函数,或者使用一个模板引擎或库来实现。我分享这个只是想告诉大家,仅凭问题中的信息,我是如何实现这个功能的。