您的代码看起来大部分都是正确的,但是需要进行一些更改来保证样式应用于 Shadow DOM 内的正确组件。
不要使用 this.renderRoot,而是直接使用 ShadowRoot 属性。如果您使用 this.attachShadow() 方法来创建 Shadow DOM,this.shadowRoot 将为您提供 Shadow DOM 的基础。 在 Shadow DOM 中使用 querySelector 时,您希望使用 ::shadow 或 ::opened 伪组件来选择 Shadow DOM 中的组件。
这是更改后的代码:
const styleString = String(styles);
const style = document.createElement("style");
style.type = "text/css";
style.innerHTML = styleString;
const styleString2 = String(guestModalStyles);
const style2 = document.createElement("style");
style2.type = "text/css";
style2.innerHTML = styleString2;
const overlayTrigger = this.shadowRoot.querySelector('overlay-trigger[type="modal"]');
if (overlayTrigger) {
const loginDialog = overlayTrigger.shadowRoot.querySelector("#login-dialog");
if (loginDialog) {
const modal = loginDialog.shadowRoot.querySelector(".modal");
if (modal) {
modal.appendChild(style);
modal.appendChild(style2);
}
}
}
要知道自己是否正确执行此操作,一种更简单的方法是临时将 css 路径 getter 函数(如下所示:从 Dom 元素获取 CSS 路径)添加到代码中(使用 console.log 或alert),然后删除代码但保存选择器。
一旦你有了一个
Element
对象,对其进行样式设置就像 一样简单
var elem = ...;
elem.style.color = "red";
您可以使用
document.styleSheets
属性来访问您的 CSS 页面(它返回一个数组,迭代数组以访问特定的 CSS 样式表),这些页面链接到您的 html 页面并使用 csspagefromstyleSheet。insertRule()
方法将样式添加到您的 CSS。