我正在尝试在影子 DOM 上应用一些样式。我有这个例子:
const existingElement = document.getElementById("foo");
const shadow = existingElement.attachShadow({ mode: "open" });
const message = document.createElement("p");
message.setAttribute("class", "text");
message.textContent = "Hello World!";
shadow.appendChild(message);
#foo::shadow .text{
color: blue; //not working
}
<div id="foo"></div>
在代码片段中,我生成了 <p class="text">Hello World!</p>
在<div id="foo"></div>
里面的shadow root中
我需要将样式应用于该类 text
但由于它位于 Shadow DOM 内部,我无法直接应用任何样式。我尝试过 ::shadow
, ::ng-deep
, ::content
但还没有结果。有什么想法吗?
最佳答案
我一直在尝试查找有关此的一些信息。我发现阴影元素与环境的其他部分完全分开。虽然如下面的统计链接
It’s worth noting that inheritable styles like color, font and line-height are still inherited in a shadow DOM. To prevent that, use all: initial or, preferably, all: revert once it has better browser support.
Styling in the Shadow DOM With CSS Shadow Parts
我研究了你的一些代码并做了类似的东西。这使得外部CSS对shadow dom产生影响。
const existingElement = document.getElementById("foo");
const shadow = existingElement.attachShadow({ mode: "open" });
const message = document.createElement("p");
message.setAttribute("part", "text");
message.textContent = "Hello World!";
shadow.appendChild(message);
#foo::part(text) {
color: blue;
}
<div id="foo"></div>
您不用 setAttribute 设置类,而是设置 part 。这似乎得到了你想要的效果。还需要说明的是,您可以在 JavaScript 中设置属性来直接应用样式。
关于javascript - 如何在 Shadow DOM 上应用样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71037363/