效果
思路
定义三个元素,文本框,下划线,占位文字。input 聚焦时通过 ~ 选中兄弟元素,利用 required 属性 + css 中的 valid 验证,判断 input 中是否有输入。写入过渡效果。
实现代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="initial-scale=1.0, user-scalable=no, width=device-width" /> <title>document</title> <style> .form-item { width: 200px; height: 30px; margin: 200px auto; position: relative; border-bottom: 2px solid #000; } .form-item input:focus, .form-item input:focus-visible, .form-item input { position: absolute; top: 0; left: 0; border: none; inset: 0; outline: none; } .form-item label { left: 0; top: 0; position: absolute; transition: 0.4s ease; } .form-item .bar { position: absolute; display: block; transform: translate(-50%, -50%); background: #5264ae; transition: 0.4s ease; bottom: -4px; left: 50%; width: 0%; height: 2px; } .form-item input:focus ~ .bar { width: 100%; } .form-item input:valid ~ label, .form-item input:focus ~ label { color: #5264ae; transform: translateY(-30px); font-size: 16px; } </style> </head> <body> <div class="form-item"> <input required id="username" type="text" /> <span class="bar"></span> <label for="username">User Name</label> </div> <script></script> </body> </html>