即使使用 all: 初始设置,Web 组件也会继承父样式

Gau*_*don 5 html javascript web-component

MVCE

您可以执行以下代码片段:

const a = document.createElement("div");

// display big red rectangle in top left
a.style.position = "absolute"; a.style.left = "10px"; a.style.top = "10px";
a.style.background = "red";
a.style.color = "green";
a.style.fontSize = "large";
document.body.appendChild(a);

// attach shadow root
a.attachShadow({mode: 'closed'}).innerHTML = `
      <style>
        :host {
          all: initial;
          display: block;
        }
      </style>

      <p>
        A paragraph element which should not inherit any styles from its parent webpage (outside the shadow DOM).
      </p>`;
Run Code Online (Sandbox Code Playgroud)

描述

我已经从lamplightdev逐字复制了影子根部分,但在各个 Stack Overflow 线程上也给出了相同的代码。由于此代码,该<p>元素不应从其父主体继承任何样式。

问题

您可以运行代码片段,看到段落元素显示为绿色,字体大小很大,这是意外的,因为我已经设置了:host { all: initial; }.

在 DevTools 中,我还可以看到段落元素显示“继承自 div”的样式规则,该规则位于我的 Web 组件之外。

问题

我希望我的 Web 组件不继承父页面样式,但为什么要这样做?

Dan*_*man 4

可以使用:host

但由于它的特异性较低,你必须强制它!important

:host {
  all: initial !important;
}

Run Code Online (Sandbox Code Playgroud)

直接来自Apple 首席 Web 组件工程师:

const a = document.createElement("div");
      a.style.background = "red";
      a.style.fontSize   = "large";
      a.style.color      = "green";

document
  .body
  .appendChild(a)
  .attachShadow({mode: 'open'})
  .innerHTML = `<style>
                  :host { all: initial !important }
                </style>
                Content which should not inherit any styles`;
Run Code Online (Sandbox Code Playgroud)

笔记:

  • open或者closedshadowRoot与CSS无关;仅当您 100% 理解自己在做什么时才
    使用。closed