概述
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>
[removed]
customElements.define('x-button', class extends HTMLElement {
constructor(){ super(); const root=this.attachShadow({mode:'open'}); root.append(document.getElementById('tpl').content.cloneNode(true)) }
})
[removed]
<!-- 外部使用 -->
<x>确定</x>
<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/::part - MDN
::slotted文档:https://developer.mozilla.org/docs/Web/CSS/::slotted - Web Components 指南:https://developer.chrome.com/docs/web-platform/web-components/

发表评论 取消回复