← 中文资源

简体中文版本

Custom Elements 自定义元素

Custom Elements 让你用作者拥有的生命周期回调(升级、属性变更、连接)定义全新 HTML 标签,原生支持、无需框架背书。

阅读英文原文

概念定义

标签注册表是可扩展的:为 my-widget 定义一个继承 HTMLElement 的类,平台就会在该标签出现的每个地方实例化它,并在明确定义的生命周期点调用你的代码。任何技术栈的标记、CSS、JavaScript 都能把它当一等公民消费。

工作机制

customElements.define 注册名称与类。升级顺序很重要:定义注册前解析的标记保持未知元素状态,注册后原地升级。observedAttributes 决定 attributeChangedCallback 的触发范围;元素在 DOM 中移动会多次触发 connectedCallback,处理器必须幂等。

使用场景

跨框架设计系统、面向第三方页面的即插组件、把旧的命令式组件包装成声明式消费。与 shadow DOM 搭配获得样式封装,与 element internals 搭配参与表单。

常见误区

构造器在标记出现时并不运行——升级发生在定义注册时,可能远晚于解析;构造器必须保持极简以兼容解析器与克隆。未升级阶段会有样式闪烁,两种状态都要设计样式。元素名必须含连字符且不得撞已有标签;断开连接时未中止的请求会跨导航泄漏。

代码示例

<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>
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Accessible confirmation dialog</title>
  <style>
    :root {
      color-scheme: light dark;
      font-family: system-ui, sans-serif;
    }

    body {
      margin: 0;
      padding: 2rem;
    }

    button {
      font: inherit;
      padding: 0.6rem 1rem;
      border: 1px solid currentColor;
      border-radius: 0.4rem;
      background: canvas;
      color: canvastext;
      cursor: pointer;
    }

    button:focus-visible {
      outline: 3px solid #4f46e5;
      outline-offset: 2px;
    }

    dialog {
      max-width: 32rem;
      border: 1px solid gray;
      border-radius: 0.75rem;
      padding: 1.5rem;
    }

    dialog::backdrop {
      background: rgb(0 0 0 / 55%);
    }

    .actions {
      display: flex;
      gap: 0.75rem;
      justify-content: flex-end;
      margin-top: 1.5rem;
    }
  </style>
</head>
<body>
  <main>
    <h1>Delete project</h1>
    <p>Deleting a project removes its deployments and environment variables.</p>
    <button type="button" id="open-dialog">Delete project…</button>
    <p id="status" role="status" aria-live="polite"></p>
  </main>

  <dialog id="confirm-dialog" aria-labelledby="dialog-title" aria-describedby="dialog-desc">
    <form method="dialog">
      <h2 id="dialog-title">Delete “Atlas”?</h2>
      <p id="dialog-desc">
        This permanently removes the project and its 12 deployments. This action cannot be undone.
      </p>
      <div class="actions">
        <button value="cancel" autofocus>Cancel</button>
        <button value="confirm">Delete permanently</button>
      </div>
    </form>
  </dialog>

  <script>
    const dialog = document.querySelector('#confirm-dialog');
    const openButton = document.querySelector('#open-dialog');
    const status = document.querySelector('#status');

    openButton.addEventListener('click', () => {
      dialog.returnValue = '';
      dialog.showModal();
    });

    dialog.addEventListener('close', () => {
      status.textContent = dialog.returnValue === 'confirm'
        ? 'Project deleted.'
        : 'Deletion cancelled.';
      openButton.focus();
    });

    dialog.addEventListener('click', (event) => {
      if (event.target === dialog) {
        dialog.close('cancel');
      }
    });
  </script>
</body>
</html>