这是我参与8月更文挑战的第18天,活动详情查看:8月更文挑战
作者:battleKing
仓库:Github、CodePen
博客:CSDN、掘金
反馈邮箱:myh19970701@foxmail.com
特别声明:原创不易,未经授权不得转载或抄袭,如需转载可联系笔者授权
背景
我们在设置表单时,一般都要设置一些 提示文字 搭配 输入框 来告知用户这里输入什么内容,此时根据提示文字的位置,我们一般有三种设计方案。
-
使用
placeholder = "请输入用户名"把提示文字设置在输入框里面- 优点:节约空间
- 缺点:当我们点击输入框,想要输入文字时,提示文字会消失,用户体验差
获得输入框焦点前.PNG
获得输入框焦点后.PNG
- 优点:节约空间
-
使用一个
<label> 用户名 </label>把提示文字设置在输入框的左边或输入框的上面- 优点:提示文字清晰
- 缺点:占用空间大
- 优点:提示文字清晰
- 使用一个
<label> 用户名 </label>把提示文字设置在输入框里面- 优点:当我们点击输入框,想要输入文字时,提示文字波浪式上移,用户体验好
- 缺点:占用空间大
获得输入框焦点前.PNG
- 优点:当我们点击输入框,想要输入文字时,提示文字波浪式上移,用户体验好
获得输入框焦点后.PNG
因为 第三种 兼顾了 时尚感 和 实用性,所以在很多新兴企业里面被广泛使用
最终效果
一、添加 HTML 文件
- 添加一层最外层的类名为
form-control的<div> form-control里面添加一层<input>form-control里面添加一层<label>
<div class="form-control">
<input type="text" required>
<label>Email</label>
</div>
二、添加 CSS 文件
先初始化页面
- 设置
*为box-sizing: border-box - 设置
body来使整个项目居中
* {
box-sizing: border-box;
}
body {
background-color: steelblue;
color: #fff;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 100vh;
overflow: hidden;
margin: 0;
}
主要的 CSS 代码
.form-control {
position: relative;
margin: 20px 0 40px;
width: 300px;
}
.form-control input {
background-color: transparent;
border: 0;
border-bottom: 2px #fff solid;
display: block;
width: 100%;
padding: 15px 0;
font-size: 18px;
color: #fff;
}
.form-control input:focus,
.form-control input:valid {
outline: 0;
border-bottom-color: lightblue;
}
.form-control label {
position: absolute;
top: 15px;
left: 0;
pointer-events: none;
}
.form-control label span {
display: inline-block;
font-size: 18px;
min-width: 5px;
transition: 0.3s cubic-bezier(0.68, -0.55, 0.265, 1.55);
}
.form-control input:focus+label span,
.form-control input:valid+label span {
color: lightblue;
transform: translateY(-30px);
}
核心逻辑
- 为
.form-control input:focus+label span和.form-control input:valid+label span添加三个属性transform: translateY(-30px);输入框获得焦点时,提示文字向上color: #4158d0;输入框获得焦点时,字体变为蓝色
- 为
.form-control label添加属性pointer-events: none;提示文字不会阻挡输入框获得焦点
- 为
.form-control label span添加属性transition: 0.3s cubic-bezier(0.68, -0.55, 0.265, 1.55);过渡动画效果
三、添加 JS 文件
主要逻辑
const labels = document.querySelectorAll('.form-control label')
labels.forEach(label => {
label.innerHTML = label.innerText
.split('')
.map((letter, idx) => `<span style="transition-delay:${idx * 50}ms">${letter}</span>`)
.join('')
})
❤️ 感谢大家
如果本文对你有帮助,就点个赞支持下吧,你的「赞」是我创作的动力。
如果你喜欢这篇文章的话,可以「点赞」 + 「收藏」 + 「转发」 给更多朋友。