示例工程 21-web-components

21-web-components/02-slots-styles/README.md

markdown · 1.1 KB

运行:21 · 插槽与样式隔离

点击「运行示例」后,左侧显示源码、右侧显示运行结果;console 输出会实时回传。

# 02 · 插槽与样式隔离
 
**演示**:`<slot>` 与具名插槽的分配、Shadow DOM 内 `p { color: red }` 不外泄、外部 `x-card p { color: green }` 只作用于 slotted 内容、`::slotted` 可以给外部节点加样式。
**怎么看**:`node scripts/serve.mjs` 后打开 <http://localhost:8080/examples/21-web-components/02-slots-styles/>,开 Console。
**预期输出**:
 
```text
默认插槽分配节点数 => 6(含空白文本节点)
Shadow 内部 p 的颜色:rgb(255, 0, 0)
Slotted p 的颜色:rgb(0, 128, 0)
插槽分配:{"title":["标题节点"],"":["默认插槽节点"]}
要点:Shadow DOM 内样式不外泄;外部样式作用于宿主与 slotted 内容,但不穿透内部。
```
 
**注意**:`::slotted()` 只能选中**顶层** slotted 节点,不能深入其后代(`::slotted(p span)` 无效)。`slotchange` 在分配节点变化时触发,但初始分配可能早于监听器注册——需要时主动读 `assignedNodes()`。`assignedNodes()` 会包含文本节点(所以示例里是 6 个,含空白),`assignedNodes({ flatten: true })` 会把 fallback 也展开。需 `http://` 协议。