【问题标题】:How to use Material Design Icons in a web component?如何在 Web 组件中使用 Material Design 图标?
【发布时间】:2020-06-15 16:01:08
【问题描述】:

看起来 mdi 在 Web 组件中不起作用,还是我遗漏了什么?

我想开发一个web组件,封装了它的依赖,添加到父文档的链接是可行的,但是违背了初衷。

<html>
<body>
<x-webcomponent></x-webcomponent>
<script>
customElements.define(
  "x-webcomponent",
  class extends HTMLElement {
    constructor() {
      super();
      this.attachShadow({ mode: "open" });
      this.shadowRoot.innerHTML = `
        <style>@import url('https://cdn.materialdesignicons.com/4.9.95/css/materialdesignicons.min.css');</style>
        <span class="mdi mdi-home"></span>
      `;
    }
  }
);
</script>
</body>
</html>

https://codepen.io/Jamesgt/pen/MWwvJaw

【问题讨论】:

  • 看起来 css @import 不起作用,我猜是因为它还引用了其他资源......
  • 在主文档中也添加
  • 谢谢,编辑了问题,外部文档中的&lt;link&gt; 有帮助,但我觉得它不是一个优雅的解决方案。
  • 也许看起来不优雅,但它是目前唯一使用字体的解决方案......

标签: web-component native-web-component css-import material-design-icons


【解决方案1】:

您要使用的字体的@font-face CSS 规则必须在主文档中声明,而不是在 Shadow DOM 中。

因为在您的情况下,它是在 materialdesignicons.min.css 文件中定义的,因此您需要通过全局 &lt;link&gt; 将其加载到主文档中。

请注意,由于浏览器的缓存,CSS 文件不会被加载两次。

或者,您可以将其添加到 Web 组件的 light DOM 中,或者您可以只声明 @font-face at-rule(从 materialdesignicons.css 文件复制)。

这是一个运行示例:

customElements.define( "x-webcomponent", class extends HTMLElement {
    constructor() {
      super()
      this.attachShadow({ mode: "open" })
      this.shadowRoot.innerHTML = `
        <link rel=stylesheet  href=https://cdn.materialdesignicons.com/4.9.95/css/materialdesignicons.min.css>
        <span class="mdi mdi-home"></span>`
    }
    connectedCallback () {
      this.innerHTML = `<style>
          @font-face {
            font-family: "Material Design Icons";
            src: url("https://cdn.materialdesignicons.com/4.9.95/fonts/materialdesignicons-webfont.woff?v=4.9.95") format("woff");
          }
       </style>`
    }
} )
&lt;x-webcomponent&gt;&lt;/x-webcomponent&gt;

【讨论】:

  • 请注意,在 sn-p 示例中,我只添加了适用于 Windows 上的 Firefox 和 Chrome 的字体。也许您需要为 Safari 和/或 Apple / Linux 添加另一种字体格式
  • 另请注意,如果您在同一页面/iframe 中插入自定义元素的多个实例,将 font-facelink 放入轻量级 DOM 将是多余的
猜你喜欢
  • 2017-11-24
  • 1970-01-01
  • 2017-02-13
  • 2019-09-27
  • 1970-01-01
  • 1970-01-01
  • 2020-03-31
  • 1970-01-01
  • 2016-08-18
相关资源
最近更新 更多