【问题标题】:How to apply styles on shadow DOM如何在 shadow DOM 上应用样式
【发布时间】:2022-02-09 03:57:22
【问题描述】:

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

在 sn-p 中,我在 <div id="foo"></div> 内部的影子根中生成 <p class="text">Hello World!</p>

我需要将样式应用于该类text,但由于它位于影子 DOM 中,因此我无法直接应用任何样式。我试过::shadow::ng-deep::content,但还没有结果。有什么想法吗?

【问题讨论】:

标签: javascript html css angular shadow-dom


【解决方案1】:

我一直在尝试查找有关此的一些信息。我能发现阴影元素与环境的其他部分完全分开。虽然作为统计下面的链接

值得注意的是,颜色、字体和行高等可继承样式仍然在 shadow DOM 中继承。为防止这种情况发生,请使用 all: initial 或者最好是 all: revert 一旦它有更好的浏览器支持。

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>

您可以设置part,而不是让 setAttribute 设置一个类。这似乎得到了你想要的效果。还需要说的是,你可以在 JavaScript 中设置一个属性来直接应用样式。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-06-12
    • 2018-09-17
    • 1970-01-01
    • 1970-01-01
    • 2016-09-18
    • 1970-01-01
    • 2019-04-25
    相关资源
    最近更新 更多