示例工程 21-web-components
21-web-components/02-slots-styles/index.html
点击「运行示例」后,左侧显示源码、右侧显示运行结果;console 输出会实时回传。
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<title>21 · 插槽与样式隔离</title>
<style>
/* 外部样式:作用于宿主与 slotted 内容,但不影响 shadow 内部的 p */
x-card p { color: rgb(0, 128, 0); }
</style>
</head>
<body>
<x-card>
<span slot="title">自定义标题</span>
<p>slotted p(外部样式,绿色)</p>
<strong>slotted strong(::slotted 下划线)</strong>
</x-card>
<script type="module">
import './x-card.js';
import { run } from './main.js';
const card = document.querySelector('x-card');
card.shadowRoot.querySelector('slot:not([name])').addEventListener('slotchange', (event) => {
console.log('默认插槽分配节点数 =>', event.target.assignedNodes().length);
});
run();
</script>
</body>
</html>