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

无需JS:聚焦时隐藏手机号标签的CSS实现方案求助

解决方案:通过CSS实现输入框聚焦时隐藏标签

优先推荐纯CSS方案,无需JS,利用CSS伪类监听聚焦状态,同时兼顾输入框有内容时的场景:

CSS 实现代码

/* 默认显示标签 */
.phone-label {
  display: block;
  /* 添加过渡动画优化视觉体验 */
  transition: all 0.2s ease;
}

/* 父容器内任意可聚焦元素(输入框/下拉框)获得焦点时,隐藏标签 */
.input-data:focus-within .phone-label {
  opacity: 0;
  visibility: hidden;
  height: 0;
  margin: 0;
  padding: 0;
}

/* 输入框有内容时,即使失去焦点也保持标签隐藏 */
.phone-input:not(:placeholder-shown) ~ .phone-label {
  opacity: 0;
  visibility: hidden;
  height: 0;
  margin: 0;
  padding: 0;
}

方案说明

  • :focus-within 会在.input-data容器内的任何可聚焦元素(input、select)获得焦点时触发,覆盖用户点击下拉框或输入框的所有场景,比单独监听input的:focus更全面。
  • 结合:not(:placeholder-shown)确保输入框填入内容后,标签持续隐藏,避免用户输入后失焦时标签重新出现干扰视觉。
  • 使用opacity+visibility+height的组合替代直接display: none,既能隐藏元素,又能避免布局突然跳动。

备选JS方案(兼容旧浏览器时使用)

如果需要兼容不支持:focus-within的旧浏览器(如IE),可使用简单的事件监听:

const phoneInput = document.querySelector('.phone-input');
const phoneLabel = document.querySelector('.phone-label');

phoneInput.addEventListener('focus', () => {
  phoneLabel.style.display = 'none';
});

phoneInput.addEventListener('blur', () => {
  if (!phoneInput.value.trim()) {
    phoneLabel.style.display = 'block';
  }
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 10:45:47