概述表单关联自定义元素允许自定义组件与原生表单协作(提交、校验、参与约束),通过 `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-elementsMDN ElementInternals 文档:https://developer.mozilla.org/docs/Web/API/ElementInternalsChrome 平台文档:https://developer.chrome.com/docs/web-platform/form-associated-custom-elements/

发表评论 取消回复