javascript - Light DOM 样式泄漏到 Shadow DOM 中

标签 javascript html css google-chrome-extension shadow-dom

我正在尝试创建一个带有 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 节中,但归结为值 initialinheritunset

关于javascript - Light DOM 样式泄漏到 Shadow DOM 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49709676/

相关文章:

javascript - 从具有多个 ID 的单个 JS 对象中获取数据并被搜索引擎索引

javascript - jcarousel 不会在图像上触发事件

javascript - 如何在 NodeJS 中持续轮询 API 以获得特定结果?

html - Flickity 轮播图片不显示

javascript - 使用 Jquery 进行图像交换

javascript - 如何将 npm 包 selenium-standalone 与 Nightmare.js 一起使用而不是下载 selenium jar?

html - 内部分页在 Firefox 中不起作用

html - 调整绝对 DIV block 的宽度

javascript - 如何将 Vue.js 作用域样式应用于通过 View 路由器加载的组件?

Javascript 将一个 onclick 事件附加到所有带有 href 变量的链接