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

如何让输入框失焦后恢复默认状态 避免标签与输入内容重叠

浮动标签输入框重叠问题修复方案

问题现象

开发表单输入框组件时,用户输入数字后输入框失去焦点,浮动提示标签会回落至输入框内部,和已输入的数字发生重叠,需要实现失焦后标签状态适配、避免内容重叠的效果。
问题效果参考截图

问题根因

原有样式仅在输入框:focus聚焦状态下触发标签上浮效果,失焦后样式直接回退到默认位置,没有判断输入框是否存在有效内容;同时代码存在标签拼写错误,将标准label标签错写为lable,也存在输入框type属性值不合法的问题。

修复实现

使用CSS原生:placeholder-shown伪类即可实现无JS的状态判断:输入框存在有效内容时placeholder会自动隐藏,此时无论是否聚焦都保持标签上浮样式,仅当输入框为空时标签才回落至默认位置。

修正后完整代码

CSS样式

.left {
  margin-left: 200px;
  margin-top: 200px;
  width: 100rem;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.input-group {
  position: relative;
}

.input {
  border-radius: 4px;
  color: #eef5db;
  background-color: transparent;
  outline: 2px solid #eef5db;
  border: 2px solid #eee;
  padding: 4rem;
  width: 30rem;
  text-align: center;
  display: block;
  margin-bottom: 3rem;
  font-size: 30px;
}

/* 修正类名拼写:原lable为错误拼写,统一改为label */
.input-label {
  position: absolute;
  top: 30px;
  left: 10px;
  font-size: 30px;
  transform: translate(10px, 10px);
  transform-origin: left;
  transition: transform 0.25s;
}

/* 聚焦、或输入框有内容时,保持标签上浮状态 */
.input:focus + .input-label,
.input:not(:placeholder-shown) + .input-label {
  transform: translate(0, -80px) scale(0.8);
  color: #000000;
}

/* 聚焦、或输入框有内容时,保持输入框高亮描边 */
.input:is(:focus, :not(:placeholder-shown)) {
  outline-color: #000000;
}

HTML结构

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Document</title>
</head>
<body>
  <section class="left">
    <div class="input-group">
      <!-- 1. 修正type属性:原age不是合法输入类型,数字输入用number;2. 添加空placeholder用于触发伪类判断 -->
      <input type="number" id="name" class="input" placeholder=" " />
      <!-- 修正label标签拼写错误 -->
      <label for="name" class="input-label">Enter your guess ...</label>
    </div>
    <div class="button">
      <input type="button" value="Check" class="check" />
      <input type="button" value="Again" class="again" />
    </div>
  </section>
</body>
</html>

关键修改点

  • 修正拼写错误:将错写的lable标签、对应类名统一改为标准label,保证样式匹配正常
  • 给输入框添加值为空格的空placeholder,用户无感知,同时可触发:placeholder-shown伪类判断输入内容是否为空
  • 调整标签上浮触发逻辑:除聚焦状态外,输入框非空时始终保持标签上浮样式,从根源避免失焦后标签和输入内容重叠
  • 修正输入框type属性:将不合法的type="age"改为数字输入场景标准的type="number"

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.02 00:01:24