使用 Shadow DOM 创建具有封装样式的 Web 组件时,可以使用 ::part 伪选择器来设置部分阴影标记的样式(https://developer.mozilla.org/en-US/docs/Web/CSS/: :部分)。
零件选择器可以用于定位嵌套阴影零件吗?
<custom-element>
#shadow-root
<div part="thats-easy"></div>
<another-custom-element part="proxy-part">
#shadow-root
<div part="target-me"></div>
</another-custom-element>
</custom-element>
目前的努力没有结果:
another-custom-element::part(target-me) { }
custom-element::part(proxy-part) another-custom-element::part(target-me) { }
custom-element::part(proxy-part another-custom-element::part(target-me)) { }
custom-element::part(proxy-part::part(target-me)) { }
```
有趣的转变,这是可能的,直到
exportparts
<style>
mux-player::part(textspan) { color: red; }
</style>
<mux-player>
<template shadowrootmode="open">
<media-poster-image exportparts="poster, img, innerspan: textspan">
<template shadowrootmode="open">
<img part="poster img" src="...">
<span part="innerspan">
This text will be red because the containing shadow host forwards innerspan to the document as "textspan" and the document style matches it.
</span>
<span part="textspan">
This text will not be red because textspan in the document style cannot match against the part inside the inner custom element if it is not forwarded.
</span>
</template>
</template>
</mux-player>
生产中的示例,其中包含多个带有 CSS 部分的嵌套自定义元素。
https://github.com/muxinc/elements/blob/main/packages/mux-player/src/template.ts
不。这不可能。这有点打破了封装原则。正确的方法是使用正确的主题。这意味着使用以下组合:
::part - For direct theming of the component
:host-context - for theming based on the context
::slotted - For styling the slotted element inside the styling
Element.matches
API 结合使用。无论组件的用户设置什么类/上下文,您都可以更改嵌套子组件的样式。
顺便说一句,即使不使用 Shadow DOM 或 Web 组件,修改颓废组件(子组件的子组件)的样式也是一种不好的做法。这会导致 CSS 变得脆弱且不可维护。
编辑注:
:host-context
并未在所有浏览器中实现,而且可能永远不会实现。