概述Shadow DOM 默认样式隔离。`::part(name)` 将内部元素标记为可被外部样式覆盖的“出口部件”;`::slotted(selector)` 用于为插槽分发的外部内容设置样式。合理使用这两者可在保持封装的前提下实现主题化。示例<!-- 组件内部 --> <template id="tpl"> <style> .btn { padding: 8px 12px; border-radius: 8px } .btn::part(icon) { /* 内部定义可导出的部件 */ } </style> <button class="btn"><span part="icon">★</span><slot></slot></button> </template> <script> customElements.define('x-button', class extends HTMLElement { constructor(){ super(); const root=this.attachShadow({mode:'open'}); root.append(document.getElementById('tpl').content.cloneNode(true)) } }) </script> <!-- 外部使用 --> <x-button>确定</x-button> <style> x-button::part(icon){ color: #e11 } x-button::slotted(span.badge){ margin-left: 4px; background: #eee } </style> 工程建议颗粒度:为需要主题化的内部元素添加 `part` 名称;避免过度暴露破坏封装。与封装:`::part` 仅能匹配带 `part` 的内部元素;`::slotted` 仅影响分发到插槽的外部内容。兼容:在不支持环境回退到自定义属性/类名配置;保持 API 一致性。参考与验证MDN `::part` 文档:https://developer.mozilla.org/docs/Web/CSS/::partMDN `::slotted` 文档:https://developer.mozilla.org/docs/Web/CSS/::slottedWeb Components 指南:https://developer.chrome.com/docs/web-platform/web-components/

发表评论 取消回复