javascript - 如何在 Shadow DOM 上应用样式

标签 javascript html css angular shadow-dom

我正在尝试在影子 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/

相关文章:

css - 背景图像重复 x 和 Y

javascript - 动态创建的输入上的 Jquery datepicker 更改第一个输入的日期

javascript - 打开图层不显示给定纬度、经度中的标签

javascript - 幻灯片播放 2 次循环后停止?

html - 将父 div 缩小到与其子 div 相同的大小

javascript - 嵌入视频播放器播放按钮一次播放所有视频播放器

html - iframe 不适用于页脚

javascript - 内联样式不适用于动态创建的输入

html - 我如何放置多个包含文本和 float 图像的 div,以便它们一次一个地沿着页面向下流动并且不重叠?

html - CSS格式化表头