前端实现material文本框效果
Supper1.效果
https://supperjoy-1318445645.cos.ap-chengdu.myqcloud.com/blog/lejian-front%20-%20%E4%B8%AA%E4%BA%BA%20-%20Microsoft%E2%80%8B%20Edge%202024-01-07%2010-39-42.mp4

2.实现代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116
| <div class="box"> <div class="login-box"> <h1 style="color: #FC6C37; text-align: center;">One Key Run</h1> <div class="form-item"> <div class="input"> <input required id="username" type="text"> <span class="bar"></span> <label for="username">手机号</label> <img src="../assets/user.svg" alt=""> </div> <div class="input"> <input required id="password" type="password"> <span class="bar"></span> <label for="username">密码</label> <img src="../assets/password.svg" alt=""> </div> <div class="btn"> 登录 </div> </div> </div> </div>
<style lang='less' scoped> .box { width: 100%; height: 100%; position: relative; }
.login-box { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); width: 500px; height: 400px; // background-color: #bfc; border-radius: 10px; }
.form-item { position: absolute; width: 80%; top: 50%; left: 50%; transform: translate(-50%, -50%); margin: auto;
input { box-sizing: border-box; width: 100%; height: 40px; border: none; outline: none; padding: 5px; background-color: transparent; color: #FC6C37; font-weight: 700; font-size: 16px; border-bottom: 2px solid grey; padding-left: 40px; }
input:valid~label, input:focus~.bar { width: 100%; } input:valid~label, input:focus~label { transform: translate(-30px,-45px); color: #FC6C37; font-weight: bold; } .input{ position: relative; margin-top: 40px; } label { position: absolute; top: 50%; left: 35px; transform: translateY(-50%); font-size: 16px; color: grey; transition: all 0.3s; } .bar { position: absolute; bottom: 0; left: 0; width: 0; height: 2px; background-color: #FC6C37; // transform: scaleX(0); transition: all 0.2s ease-in-out; } .btn{ width: 100%; background-color: #FC6C37; border-radius: 10px; height: 40px; text-align: center; line-height: 40px; color: #fff; margin-top: 30px; cursor: pointer; } img{ position: absolute; top: 0; left: 0; width: 30px; } } </style>
|
3.关键
使用浏览器自带的判断文本框是否为空来控制动画
1
| <input required id="username" type="text">
|
1 2 3 4 5 6 7 8 9 10 11
| input:valid~label,
input:focus~label {
transform: translate(-30px,-45px);
color: #FC6C37;
font-weight: bold;
}
|