我正在尝试创建一个带有 float 小部件的 Chrome 扩展程序。为此,我必须将我的元素与页面的其余部分隔离开来。 Shadow DOM 看起来非常适合它,但它并没有达到我的预期。
这是我的内容脚本:
内容.js
var lightDom = document.createElement('style');
lightDom.innerText = 'div { color: red }';
document.body.appendChild(lightDom);
var shadowDom = document.createElement('div');
document.body.appendChild(shadowDom);
var shadowRoot = shadowDom.attachShadow({'mode': 'open'});
shadowRoot.innerHTML = `
<style>
div {
background-color: blue;
}
</style>
<div>Shadow!</div>
`;
影子 DOM 内的 div 应该有黑色文本,但它有红色文本。我做错了什么吗?
最佳答案
为什么会这样?
Light DOM 中的 CSS 选择器无法到达 shadow DOM 中的元素。但是当 CSS 属性的值为 inherit
时,这是 color
的默认值,shadow DOM 仍然会继承 light DOM。
From the CSS Scoping specification
3.3.2 Inheritance
The top-level elements of a shadow tree inherit from their host element. The elements in a distribution list inherit from the parent of the content element they are ultimately distributed to, rather than from their normal parent.
如何防止它发生?
您可以通过使用 initial
值来防止属性表单的值被继承。
From the CSS Cascading and Inheritance specification
7.3.1. Resetting a Property: the initial keyword
If the cascaded value is the initial keyword, the property’s initial value becomes its specified value.
每个属性的初始值记录在其定义的规范中。color
记录在 CSS Color specification 中。它的初始值是取决于用户代理
,对于大多数用户代理,这将是黑色
。
您可以将initial
分配给您不想继承其值的每个属性。或者您可以将 all
的值设置为 initial
,如下所示:
.selector
{
all: initial;
}
all
属性在与 initial 关键字相同的规范中定义如下。
3.1. Resetting All Properties: the all property
The all property is a shorthand that resets all CSS properties except direction and unicode-bidi. It only accepts the CSS-wide keywords.
“CSS 范围内的关键字”在 CSS 3 values specification 中定义在 3.1.1 节中,但归结为值 initial
、inherit
和 unset
。
关于javascript - Light DOM 样式泄漏到 Shadow DOM 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49709676/