提问人:Dennis 提问时间:11/17/2023 最后编辑:Dennis 更新时间:11/20/2023 访问量:36
将 fontawesome 添加到 webcomponent 的 shadowroot
Add fontawesome to shadowroot of webcomponent
问:
我创建了一个创建 Web 组件的 JS 脚本。该 Web 组件使用了 Font Awesome 图标。当我将 Font Awesome 库包含在我的 HTML 头部时,图标可以毫无问题地工作。但我不希望它们被添加到 HTML 中,我希望它们在我的组件的阴影中。
我的 JS 文件有一个 render() 函数,所有 HTML 都在其中。我还添加了字体真棒 css 的获取,但这不起作用。我也试图简单地链接到那里的 css,但这也不起作用。
下面是我的代码的最小示例:
render() {
fetch('https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.1/css/all.min.css')
.then(response => response.text())
.then(cssText => {
// Inject the CSS text into the shadow DOM's <head> element
const shadowHead = this.shadowRoot.querySelector('head');
const styleElement = document.createElement('style');
styleElement.textContent = cssText;
shadowHead.appendChild(styleElement);
});
// Create the component's structure and styles
this.shadowRoot.innerHTML = `
<head>
<style>
* {
font-family: Arial, sans-serif;
}
.title {
color: #366BAB;
font-size: 1rem;
}
</style>
</head>
<div>
<h1 class="title">Lorem ipsum</h1>
</div>
`;
}
结果:
未添加 CSS。出于测试目的,我创建了一个类为 .head 的 div 并将 querySelector 更改为“.head”,CSS 已添加到该 div 中,但未应用,图标无法以这种方式工作。
新发现:
它们的图标都显示为正方形,当我检查这样的正方形时,我看到实际的CSS被注入了正确的链接。请参见下面的屏幕截图
答:
2赞
Danny '365CSI' Engelman
11/17/2023
#1
您必须问自己的第一个问题:我的 Web 组件真的需要 shadowDOM 吗?
如果是这样,您必须在主文档和 shadowDOM 中加载 FontAwesome
<fa-icon is="check"></fa-icon>
<fa-icon is="square-check"></fa-icon>
<fa-icon is="circle-check"></fa-icon>
<fa-icon></fa-icon>
<script>
let element = (tag,p={}) => Object.assign(document.createElement(tag),p);
customElements.define('fa-icon', class extends HTMLElement {
constructor() {
let version = "[email protected]";
let href = `https://cdn.jsdelivr.net/npm/@fortawesome/${version}/css/all.min.css`;
let linkFontAwesome = () => element("link", {rel: "stylesheet", href });
let hasFontAwesome = document.querySelector(`link[href="${href}"]`);
if (!hasFontAwesome) document.head.append( linkFontAwesome() );
super()
.attachShadow({mode:'open'})
.append(
linkFontAwesome(),
element("icon")
);
}
connectedCallback() {
this.style.display = "inline-block";
this.icon = this.icon;
this.onclick = (evt) => alert( this.icon );
}
get icon() {
return this.getAttribute("is") || "gear";
}
set icon(icon){
this.shadowRoot.querySelector("icon").innerHTML = `<i class="fa fa-${icon}"></i>`;
}
});
</script>
评论
0赞
Dennis
11/20/2023
这回答了我的问题。FA 库需要包含在主文档和 Web 组件本身中。
评论
<head>