---
title: "ElementInternals 与表单关联自定义元素:策略与实践"
keywords:
- ElementInternals
- formAssociated
- 自定义元素
- 表单校验
- 可访问性
description: "说明表单关联自定义元素的实现方式、ElementInternals 的能力(值、校验、无障碍)、与原生表单协作及回退策略,并提供示例。"
categories:
- 文章资讯
- 编程技术
---
概述
表单关联自定义元素允许自定义组件与原生表单协作(提交、校验、参与约束),通过 ElementInternals 管理值与有效性并同步到表单。
示例
<my-input name="account"></my-input>
<script>
class MyInput extends HTMLElement {
static formAssociated = true
#internals = this.attachInternals()
constructor() { super(); this.value = '' }
connectedCallback() {
this.innerHTML = '<input type="text" />'
this.querySelector('input').addEventListener('input', e => {
this.value = e.target.value
this.#internals.setFormValue(this.value)
this.#internals.setValidity(this.value ? {} : { valueMissing: true }, this.value ? '' : '必填')
})
}
}
customElements.define('my-input', MyInput)
</script>
工程建议
- 有效性与提示:使用
setValidity与自定义消息;与原生约束 API 对齐。 - 无障碍:暴露角色与标签;保证键盘与读屏一致性。
- 兼容:特性检测后启用;旧浏览器回退到常规表单控件或包裹策略。
参考与验证
- HTML 规范(Form-associated custom elements):https://html.spec.whatwg.org/multipage/custom-elements.html#form-associated-custom-elements
- MDN ElementInternals 文档:https://developer.mozilla.org/docs/Web/API/ElementInternals
- Chrome 平台文档:https://developer.chrome.com/docs/web-platform/form-associated-custom-elements/

发表评论 取消回复