← 中文资源

简体中文版本

Shadow DOM

Shadow DOM 为元素附加封装的 DOM 子树:样式作用域隔离、slot 内容分发受控,让组件的标记不会与宿主页面的样式相互冲突。

阅读英文原文

概念定义

Shadow DOM 是封装原语:为宿主元素挂载一个隐藏子树。内部样式不外泄,外部选择器也无法进入——除非经由自定义属性与 part 钩子;页面内容通过 slot 分发进来,但样式归属仍在页面侧。

工作机制

open 与 closed 模式只影响宿主元素上能否访问 shadowRoot。可继承属性(字体、颜色)照常穿透边界,自定义属性是显式传入设计令牌的通道,part 属性向页面暴露可样式化钩子。事件默认在宿主处重定向,composed 事件可继续向外冒泡。

使用场景

跨团队跨应用分发的设计系统、嵌在第三方页面上的小组件、以及一切“页面 CSS 不应决定内部结构”的场景。与 custom elements 提供生命周期,与外置令牌契约提供主题能力。

常见误区

Shadow DOM 不对 JavaScript 隐藏标记,只是样式与组合的作用域封装,树仍可遍历。插槽并未把内容拷进影子树:节点留在 light DOM。若不设计自定义属性与 part 契约就全盘影子化,消费方会与封装对抗;表单参与与测试选择器也需要额外接线。

代码示例

<custom-counter start="10" step="2"></custom-counter>

<script>
  class CustomCounter extends HTMLElement {
    static get observedAttributes() {
      return ['start', 'step'];
    }

    constructor() {
      super();
      this._count = 0;
      this._step = 1;
      const shadow = this.attachShadow({ mode: 'open' });
      shadow.innerHTML = `
        <style>
          :host { display: inline-flex; gap: 0.5rem; align-items: center; }
          button { padding: 0.25rem 0.5rem; cursor: pointer; }
          .value { font-weight: bold; min-width: 2rem; text-align: center; }
        </style>
        <button id="dec">-</button>
        <span class="value">0</span>
        <button id="inc">+</button>
      `;
    }

    connectedCallback() {
      this._count = parseInt(this.getAttribute('start') || '0');
      this._step = parseInt(this.getAttribute('step') || '1');
      this._update();

      this.shadowRoot.getElementById('inc')
        .addEventListener('click', () => this._increment());
      this.shadowRoot.getElementById('dec')
        .addEventListener('click', () => this._decrement());
    }

    attributeChangedCallback(name, oldVal, newVal) {
      if (name === 'step') this._step = parseInt(newVal || '1');
    }

    disconnectedCallback() {
      console.log('Counter removed from DOM');
    }

    _increment() { this._count += this._step; this._update(); }
    _decrement() { this._count -= this._step; this._update(); }
    _update() {
      this.shadowRoot.querySelector('.value').textContent = this._count;
      this.dispatchEvent(new CustomEvent('change', {
        detail: { value: this._count }
      }));
    }
  }

  customElements.define('custom-counter', CustomCounter);

  document.querySelector('custom-counter')
    .addEventListener('change', e => console.log('Count:', e.detail.value));
</script>
<!-- Define a custom element with slots -->
<template id="card-template">
  <style>
    .card { border: 1px solid #ccc; border-radius: 8px; padding: 1rem; }
    .card-header { font-weight: bold; border-bottom: 1px solid #eee; }
    .card-footer { border-top: 1px solid #eee; margin-top: 0.5rem; }
  </style>
  <div class="card">
    <div class="card-header">
      <slot name="header">Default Header</slot>
    </div>
    <div class="card-body">
      <slot></slot>
    </div>
    <div class="card-footer">
      <slot name="footer">Default Footer</slot>
    </div>
  </div>
</template>

<!-- Using the custom element with slot content -->
<custom-card>
  <span slot="header">My Card Title</span>
  <p>This goes in the default slot (body).</p>
  <p>Multiple elements can go here.</p>
  <button slot="footer">Action Button</button>
</custom-card>

<custom-card>
  <span slot="header">Another Card</span>
  <img src="photo.jpg" alt="Photo" slot="body">
</custom-card>

<script>
  class CustomCard extends HTMLElement {
    constructor() {
      super();
      const template = document.getElementById('card-template');
      const shadow = this.attachShadow({ mode: 'open' });
      shadow.appendChild(template.content.cloneNode(true));
    }
  }
  customElements.define('custom-card', CustomCard);
</script>