You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MDC Web Textfield组件点击输入时外框(outline)消失问题求解

你遇到的外框无法正常显示的问题由两个错误导致:

  • 第一是Outlined样式的TextField DOM结构不符合MDC规范:
    1. mdc-notched-outline__leading、mdc-notched-outline__notch、mdc-notched-outline__trailing三个类的元素必须是mdc-notched-outline元素的直接子元素,你当前的代码里这几个元素和mdc-notched-outline平级,嵌套错误。
    2. 输入框input.mdc-text-field__input必须放在label.mdc-text-field容器内部,你当前把它放到了容器外部,导致组件无法正确监听输入状态修改外框样式。
  • 第二是JS初始化逻辑冗余冲突:MDCTextField实例化时会自动初始化内部的所有子组件(NotchedOutline、FloatingLabel、LineRipple),单独实例化这些子组件会导致状态冲突,反而影响组件正常表现。

修正后的Pug模板代码

div.mdc-layout-grid__cell--span-4.mdc-layout-grid__cell--span-12-phone.mdc-layout-grid__cell--span-12-tablet
  label.mdc-text-field.mdc-text-field--filled
    span.mdc-text-field__ripple
    span.mdc-floating-label(id="first_name") First Name :
    input.mdc-text-field__input(type="text" aria-labelledby="first_name")
    span.mdc-line-ripple
div.mdc-layout-grid__cell--span-4.mdc-layout-grid__cell--span-12-phone.mdc-layout-grid__cell--span-12-tablet
  label.mdc-text-field.mdc-text-field--outlined
    span.mdc-notched-outline
      span.mdc-notched-outline__leading
      span.mdc-notched-outline__notch
        span.mdc-floating-label(id="last_name") Surname :
      span.mdc-notched-outline__trailing
    input.mdc-text-field__input(type="text" aria-labelledby="last_name")

修正后的JS初始化代码

const textFields = [].map.call(document.querySelectorAll('.mdc-text-field'), function (el) {
    return new mdc.textField.MDCTextField(el);
});

修改完成后刷新页面即可恢复外框的正常交互表现。

内容的提问来源于stack exchange,提问作者Abby Ammo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 01:15:04