为什么 Web 组件在某些情况下 DOM 样式 "leaking" 为 DOM 的文本,而样式仍然有效?

Why are web components light DOM style "leaking" as text to the DOM in certain cases while styling still functions?

在学习 Web 组件时,我遇到了一个特殊情况,CSS 样式 "leaking" 到 DOM 显然是文本节点,但它似乎仍然有效。在提供的图像中查看黄色箭头所指的 CSS 文本如何在 DOM 中显示为文本节点。这可以通过改变 *(泄漏)和 div(不泄漏)之间的 CSS 选择器来测试。

这怎么解释?查看代码和图像,如果您想快速尝试,https://codepen.io/veksi/pen/WNvMOYg 处有一支笔,您可以在其中切换选择器(已使用 Firefox 和 Chrome 测试)。

<this-test>
  <div>
    <p>Some test text in div.</p>
    <p>Some more some text in div.</p>
    <p>And even more some text in div.</p>
  </div>

  <section>
    <p>Some test text in section.</p>
    <p>Some more some text in section.</p>
    <p>And even more some text in section.</p>
  </section>
</this-test>

const template = document.createElement('template');

template.innerHTML = `
  <style>
    /* Why does changing the following selector to
           this-test > *
       i.e. to the asterisk to match all elements, "leak" out while otherwise seem to work? */
    this-test > div {
      display: flex;
      flex-direction: column;
      color: hotpink;
    }

    p {
      background: #abcabc;
      padding: 1rem;
      border: 0;
      font-size: 1.5rem;
    }
  </style>  
`;

class ThisTest extends HTMLElement {
  constructor() {
    super();

    //Note that shadow root is not used.
    this.appendChild(template.content.cloneNode(true));       
  }  
}

window.customElements.define('this-test', ThisTest);

与自定义 Elements/Web 组件无关

所有 DOM 元素都有 display: 设置

默认 、 <script> 和 <style> 标签有 <code>display:none</code></strong></p> <p>当您使用 <code>* {display:block}</code>(或任何设置)时<br> 这些通常隐藏的元素的<strong>内容</strong> 现在显示在页面中</p> <p>显示 <strong>内联</strong> STYLE 和 SCRIPT 标签内容的有趣方式:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre><code><title desc=" Title of this HTML document">Hello DOM World!</title> <script desc=" Logs text to the DEV console">console.log("Hello from SCRIPT")</script> <style> *{ display:block; font-size:9px; color:red; } title, script{ font-size:2em; color:blue; } *:hover:after{ display:inline; content:attr(desc); color:green; } </style> </code></pre> </div> </div> </p> <p>第一个红色样式块是 SO 在代码段中注入的内容</p> </section> </div> </div> <div class="line"></div> <div id="footer">©2023 WhoseBug</div> </body> </html>