【问题标题】:How to load google font in LitElement如何在 LitElement 中加载谷歌字体
【发布时间】:2019-12-20 17:05:57
【问题描述】:

我正在使用 LitElement,我正在尝试在元素级别加载 google-font。

我尝试在connectedCallback 事件中以 HTML 文字形式返回它,但它不起作用。 我无法在get styles() 方法中做到这一点。

<link...> 语句应该放在代码的什么位置?

【问题讨论】:

标签: lit-element polymer-3.x google-fonts lit-html


【解决方案1】:

您可以轻松地在 index.html 中导入 google 字体:

<link href="https://fonts.googleapis.com/css?family=Kaushan+Script&display=swap" rel="stylesheet">

或者你可以创建一个通用的 style.js 文件并包含它:

const $_documentContainer = document.createElement('template');

$_documentContainer.innerHTML = `<style>
 @import url('https://fonts.googleapis.com/css?family=Kaushan+Script');
 html,
 body {
  font-family: 'Roboto', Arial, sans-serif;
  height: 100%;
  margin: 0;
 }
 ...


</style>`;

document.head.appendChild($_documentContainer.content);
var importDoc = window.document;
var style = importDoc.querySelector('style');
document.head.appendChild(style);

或:

class MyElement extends LitElement {
  render() {
    return html`
      <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Kaushan+Script">
    `;
  }
}

demo(在我导入 Kaushan+Script 时看到红色的 a 标签)

【讨论】:

  • 谢谢。我实际上是在寻找一种在组件中而不是在索引级别延迟加载字体的解决方案。某些字体可能只有特定组件才需要。我相信您的两个选项都会预先加载字体。
  • @JoceM 你找到解决方案了吗?我也在寻找一种在组件内部而不是在索引级别加载字体的方法......
【解决方案2】:

您可以通过在模板中添加&lt;link&gt; 元素来导入外部样式表,详情请参阅Import an external stylesheet

这是 StackBlitz 上的演示。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-10
    • 1970-01-01
    • 2013-07-16
    • 2017-01-31
    • 1970-01-01
    • 2017-08-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多