如何在Web组件中使用Material Design图标? [英] How to use Material Design Icons in a web component?
问题描述
看起来像MDI在Web组件内部无法运行,还是我错过了什么?
Looks like that mdi is not working inside web components, or do I miss something?
我想开发一个封装其依赖项的Web组件,将链接添加到父文档中即可,但是它违反了最初的意图.
I want to develop a web component that encapsulates it's dependencies, adding the link to the parent document works, but it violates the original intent.
<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
推荐答案
要使用的字体的@font-face
CSS规则必须在主文档中声明,而不是在Shadow DOM中声明.
The @font-face
CSS at-rule for the font you want to use must be declared in the main document, not in the Shadow DOM.
由于在您的情况下它是在 materialdesignicons.min.css 文件中定义的,因此您需要通过全局<link>
将其加载到主文档中.
Because in your case it is defined in the materialdesignicons.min.css file, you'll need to load it in the main document via a global <link>
.
请注意,由于浏览器的缓存,CSS文件不会被加载两次.
Note that the CSS file won't be loaded twice thanks to the browser's cache.
或者,您可以将其添加到Web组件的轻型DOM中,也可以只声明@font-face
规则(从 materialdesignicons.css 文件复制).
Alternately, you could add it in the light DOM of the web component, or you could just declare the @font-face
at-rule (copied from the materialdesignicons.css file).
这是一个正在运行的示例:
Here is a running example:
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>`
}
} )
<x-webcomponent></x-webcomponent>
这篇关于如何在Web组件中使用Material Design图标?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!