登录
首页 >  文章 >  前端

自定义HTML元素教程:JS创建与使用方法

时间:2026-01-29 19:03:43 206浏览 收藏

怎么入门文章编程?需要学习哪些知识点?这是新手们刚接触编程时常见的问题;下面golang学习网就来给大家整理分享一些知识点,希望能够给初学者一些帮助。本篇文章就来介绍《自定义HTML元素教程:如何用JavaScript创建和使用》,涉及到,有需要的可以收藏一下

Custom Elements 是 Web Components 的核心,需继承 HTMLElement、含短横线命名,用 customElements.define() 注册;构造函数必须调用 super() 初始化 this,attributeChangedCallback 仅响应 observedAttributes 中声明的属性变更,且受浏览器兼容性与 DOM 结构限制。

javascript的custom elements如何定义_如何创建和使用自己的html元素【教程】

Custom Elements 是 Web Components 的核心之一,它允许你定义自己的 HTML 标签,但不是靠封装或模拟,而是真正注册进浏览器的 DOM 系统——这意味着 document.createElement('my-button') 能返回合法元素,instanceof 会通过校验,且能被 querySelector、框架的 ref、甚至原生表单逻辑识别。

如何用 customElements.define() 注册一个自定义元素

必须继承 HTMLElement(或其子类如 HTMLButtonElement),且类名中必须含短横线(-),这是强制语法限制,否则抛出 DOMException: The element name must contain a hyphen

  • 类不能是匿名函数或箭头函数,必须有命名(哪怕只是 class MyCard extends HTMLElement
  • 注册前必须先声明类,顺序不能颠倒;若重复注册同一名称,会报错 Failed to execute 'define' on 'CustomElementRegistry': the name "x-foo" has already been used
  • 名称不能以 x- 开头再加短横线(如 x-foo-bar 合法,x--foo 不合法),也不能是保留名(如 htmlslottemplate
class MyCounter extends HTMLElement {
  constructor() {
    super();
    this.count = 0;
    this.attachShadow({ mode: 'open' });
    this.shadowRoot.innerHTML = `
      <style>button { font-size: 14px; }</style><button><slot></slot>: ${this.count}</button>
    `;
  }

  connectedCallback() {
    this.shadowRoot.querySelector('button').addEventListener('click', () => {
      this.count++;
      this.shadowRoot.querySelector('button').textContent = `${this.textContent}: ${this.count}`;
    });
  }
}

customElements.define('my-counter', MyCounter);

为什么必须用 constructor + super()

因为 Custom Element 构造函数在 DOM 初始化阶段被调用(比如解析 HTML 字符串时),此时元素尚未插入文档,也无父节点。不调用 super() 会导致 this 未初始化,后续所有操作(如 attachShadowsetAttribute)都会失败,并静默报错或直接崩溃。

  • connectedCallbackdisconnectedCallback 可以安全访问 this.parentNode,但 constructor 里永远不能
  • attributeChangedCallback 的触发前提是:该属性在 observedAttributes 中声明,且元素已定义完成——也就是说,它不会在 constructor 执行期间触发
  • 不要在 constructor 里调用 this.innerHTML 或读取 this.children,它们为空;应改用 slotinnerHTML 写入 shadow DOM

如何让自定义元素支持 HTML 属性并响应变更

仅靠 setAttribute 不会自动触发更新,必须显式监听属性变化。浏览器只会在属性值字符串发生变化时调用 attributeChangedCallback,且仅限于 observedAttributes 返回的数组中列出的属性名。

  • 属性名自动转为小写(My-Propmy-prop),所以 observedAttributes 必须写小写形式
  • 若属性初始值来自 HTML(如 ),attributeChangedCallback 会在 connectedCallback 前触发一次
  • 注意:布尔属性(如 disabled)的变更,newValue""(空字符串)而非 true;需用 this.hasAttribute('disabled') 判断
class MyInput extends HTMLElement {
  static get observedAttributes() {
    return ['value', 'disabled'];
  }

  attributeChangedCallback(name, oldValue, newValue) {
    switch (name) {
      case 'value':
        this.input.value = newValue || '';
        break;
      case 'disabled':
        this.input.disabled = this.hasAttribute('disabled');
        break;
    }
  }

  constructor() {
    super();
    this.attachShadow({ mode: 'open' });
    this.shadowRoot.innerHTML = `&lt;input type=&quot;text&quot; class=&quot;input&quot;&gt;`;
    this.input = this.shadowRoot.querySelector('input');
  }
}

customElements.define('my-input', MyInput);

使用时要注意哪些兼容性与陷阱

Chrome / Edge / Safari 原生支持良好,Firefox 从 63+ 支持,但 IE 完全不支持(无 polyfill 可完美还原行为)。即便现代浏览器,也有几个容易忽略的点: