我正在使用Web组件。我有下面的html结构
<div class="test">
#shadow-root (open)
<overlay-trigger type="modal">
<div id = "login-dialog">
#shadow-root (open)
<div id = "modal">
字符串
我有以下代码
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;
let host = this.renderRoot?.querySelector('overlay-trigger[type="modal"]')?.querySelector("#login-dialog")?.shadowRoot?.querySelector(".modal");
if (host) {
host?.appendChild(style);
host?.appendChild(style2);
}
型
如何向模式元素添加样式?class =“modal”的那个?我在上面做吗?
3条答案
按热度按时间rm5edbpk1#
一个更简单的方法就是添加一个css路径getter函数(如下所示:Get CSS path from Dom element)添加到您的代码中(使用console.log或alert),然后删除代码,但保存选择器。
有了
Element
对象后,对其进行样式化就像字符串
db2dz4w82#
您的代码看起来大部分都是正确的,但是有几个更改可以确保样式应用于Shadow DOM中的正确组件。
与其使用这个.renderRoot,不如直接使用shadowRoot属性。如果您正在使用this.attachShadow()技术来创建Shadow DOM,则this.shadowRoot将为您提供Shadow DOM的基础。在Shadow DOM中使用querySelector时,您希望使用::shadow或::opened伪组件来选择Shadow DOM中的组件。
更改代码:
字符串
bwleehnv3#
你可以使用
document.styleSheets
属性来访问你的CSS页面(它返回一个数组,遍历数组来访问特定的CSS样式表),这些页面链接到你的html页面,并使用csspagefromstyleSheet。insertRule()
方法来添加样式到你的CSS。