为什么 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:
设置
默认 、
在学习 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:
设置
默认