轻型DOM风格泄漏到Shadow DOM中 [英] Light DOM style leaking into Shadow DOM
问题描述
我正在尝试使用浮动小部件创建Chrome扩展程序。要做到这一点,我必须将我的元素与页面的其余部分隔离开来。 Shadow DOM看起来非常适合它,但它没有达到我的预期。
I am trying to create a Chrome extension with a floating widget. To do that, I have to isolate my element from the rest of the page. Shadow DOM looks like a perfect fit for that, but it isn't doing what I expected.
这是我的内容脚本:
content.js
content.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>
`;
shadow DOM中的div应该有黑色文本,但它有红色文本。我做错了吗?
The div inside the shadow DOM should have black text, but it has red text instead. Am I doing something wrong?
推荐答案
为什么会这样?
Light DOM中的CSS选择器无法到达shadow DOM内的元素。但是当CSS属性的值继承
,这是 color
的默认值时,shadow DOM仍将继承来自轻型DOM的那些。
Why is this happening?
CSS selectors in Light DOM are prevented from reaching elements inside shadow DOM. But when a CSS property has the value inherit
, which is the default value of color
, the shadow DOM will still inherit those from the light DOM.
3.3.2继承
阴影树的顶级元素继承自其宿主元素。
分发列表中的元素继承自最终分发给它们的内容元素的父元素,而不是从它们的普通父元素继承。
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 $ c来阻止继承属性表单的值$ c> value。
7.3.1。重置属性:初始关键字
如果级联值是初始关键字,则属性的初始值将成为其指定值。
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颜色规范及其初始值取决于用户代理
,对于大多数用户代理,这将是黑色
。
The initial value of each property is documented in the specification it is defined in. color
is documented in the CSS Color specification and its initial value is depends on user agent
, for most user agents this will be black
.
您可以分配初始
到您不想继承其值的每个属性。或者您可以将所有
的值设置为 initial
,如下所示:
You can assign initial
to each property you don't want to inherit its value. Or you can set the value of all
to initial
, like so:
.selector
{
all: initial;
}
所有
属性在与初始关键字相同的规范中定义如下。
The all
property is defined as follows in the same spec as the initial keyword.
3.1。重置所有属性:all属性
all属性是一种速记,可以重置除direction和unicode-bidi之外的所有CSS属性。它只接受CSS范围的关键字。
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-wide keywords在 3.1.1中的CSS 3值规范,但归结为值 initial
,继承
和取消设置
。
"CSS-wide keywords" is defined in CSS 3 values specification in section 3.1.1, but comes down to the values initial
, inherit
and unset
.
这篇关于轻型DOM风格泄漏到Shadow DOM中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!