如何不使用Material UI库,用HTML/CSS/React实现同类文本输入框?
浮动占位符输入框实现方案
核心思路
- 输入框与label标签共用一个相对定位的父容器,由父容器模拟外边框样式
- label默认定位在输入框内部充当占位符,设置过渡动画属性
- 监听输入框的:focus状态、以及输入值非空状态,触发label的位移、缩放样式变更,实现上浮到边框位置的效果
原生HTML+CSS实现
<div class="form-field"> <input type="text" id="username" required> <label for="username">用户名</label> </div>
.form-field { position: relative; margin: 20px 0; width: 300px; } .form-field input { width: 100%; padding: 15px 12px; font-size: 16px; border: 1px solid #ccc; border-radius: 4px; outline: none; background: transparent; } .form-field label { position: absolute; left: 12px; top: 50%; transform: translateY(-50%); font-size: 16px; color: #999; pointer-events: none; transition: all 0.2s ease; background: #fff; padding: 0 4px; } /* 输入框聚焦、输入内容非空时的label样式 */ .form-field input:focus ~ label, .form-field input:valid ~ label { top: 0; transform: translateY(-50%) scale(0.8); color: #1976d2; } .form-field input:focus { border-color: #1976d2; }
- 原生实现依靠input的
required属性和:valid伪类判断是否有输入,无需额外JS代码即可运行。
React 函数组件实现
import { useState } from 'react'; import './FloatingInput.css'; const FloatingInput = ({ label, type = 'text', name, id }) => { const [value, setValue] = useState(''); const [isFocused, setIsFocused] = useState(false); const handleChange = (e) => { setValue(e.target.value); }; return ( <div className="form-field"> <input type={type} id={id} name={name} value={value} onChange={handleChange} onFocus={() => setIsFocused(true)} onBlur={() => setIsFocused(false)} /> <label className={`${isFocused || value ? 'floating' : ''}`} htmlFor={id} > {label} </label> </div> ); }; export default FloatingInput;
对应的CSS新增floating类即可:
.form-field label.floating { top: 0; transform: translateY(-50%) scale(0.8); color: #1976d2; }
- React版本通过状态控制样式,适配性更强,可支持自定义校验规则、特殊输入场景的需求。
内容的提问来源于stack exchange,提问作者Jamal Fakhriddinov
相关产品推荐
相关产品推荐

