无需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
相关产品推荐
相关产品推荐

