theme: scrolls-light
highlight: atom-one-dark
介绍
大家好,我是爱吃鱼的桶哥Z,在日常的开发中,我们经常会与表单元素打交道,其中最常用的莫过于账号密码的输入框
,今天我们就一起来学习一下丰富的自定义输入框
交互动画。首先还是先来看一下最终的实现效果,如下所示:
在上图可以看到,当我们的输入框
没有被激活时,输入框
的标签名是展示在输入框上的;当输入框
被激活后,输入框
的标签名会向上移动,如果输入框
没有内容,点击其它位置时,输入框
的标签又会回到之前的位置,反之则不会有变化。像这样的交互效果可以给用户极强的交互体验,那么我们该如何实现这个效果呢?一起来看看吧!
实现自定义输入框交互动画
在上图中已经可以看到大致的运行效果了,接下来咱们就需要编写相关的 html
和 css
代码了。首先添加相关的 html
代码,如下:
<div class="container">
<div class="inputBox">
<input type="text" required="required" />
<span>UserName</span>
<i></i>
</div>
</div>
在上述的 html
代码中,需要特别注意的是给 input
标签添加一个 required
为 required
的属性,这告诉当前 input
该值是必填的。接下来就需要编写 css
代码了,让我们一起看一下基础的 css
代码,如下:
*{
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: Arial, Helvetica, sans-serif;
}
body {
display: flex;
align-items: center;
justify-content: center;
min-height: 100vh;
background: linear-gradient(45deg, #2196f3, #ff4685);
}
通过给 body
标签添加一个 background
属性,并设置属性值为 linear-gradient
,从而产生一个渐变的效果,如下图所示:
通过上图可以看到渐变的背景色旋转了45度,接下来就需要实现 input
相关的样式了,相关 css
代码如下:
.container .inputBox {
position: relative;
width: 350px;
margin-bottom: 36px;
}
.container .inputBox input {
position: relative;
padding: 8px 10px;
width: 100%;
border: none;
outline: none;
background: transparent;
color: #fff;
font-size: 1.25em;
letter-spacing: 0.05em;
z-index: 2;
}
.container .inputBox span {
position: absolute;
left: 0;
padding: 10px 0;
pointer-events: none;
font-size: 1em;
transition: .5s;
color: #333;
letter-spacing: .05em;
}
.container .inputBox input:valid ~ span,
.container .inputBox input:focus ~ span {
font-size: .85em;
transform: translateY(-32px);
}
.container .inputBox i {
position: absolute;
bottom: 0;
left: 0;
width: 100%;
height: 3px;
background: linear-gradient(45deg, #2196f3, #ff4685);
transition: .5s;
z-index: 1;
border-radius: 4px;
pointer-events: none;
}
.container .inputBox input:valid ~ i,
.container .inputBox input:focus ~ i {
height: 100%;
box-shadow: inset0 0 10px rgba(0, 0, 0, .25);
}
我们给页面中的 input
设置了相关属性,其中主要是需要去除 input
默认的 border
和 outline
属性,然后给 inputBox
中的 i
元素设置相关的宽度和背景色,这样当 input
框没有被激活前,这个 i
标签就以一条渐变的横线展示在页面中,具体的效果如下所示:
通过上述的代码及展示的图片效果,咱们不难看出,其实当 input
被激活时,是使用了一个 i
标签,通过改变 i
标签的高度从而实现了这个动画的效果。
当然,一般的输入框可不仅只有账号输入,还需要密码的输入框,因此咱们再来修改一下 html
代码,让密码输入框也能展示出来,html
代码如下:
<div class="container">
<div class="inputBox">
<input type="text" required="required" />
<span>UserName</span>
<i></i>
</div>
<div class="inputBox">
<input type="password" required="required" />
<span>PassWord</span>
<i></i>
</div>
</div>
最后需要修改一下 inputBox
标签向下的距离,否则当 span
标签升起来的时候会被上面的内容盖章,简单的修改 css
代码即可,如下:
.container .inputBox {
position: relative;
width: 350px;
margin-bottom: 36px;
}
.container .inputBox:last-child {
margin-bottom: 0;
}
最终实现的完整效果及代码在这里进行查看:
代码片段
总结
在日常的开发中,input
输入框是经常与用户打交道的,如果交互动画做的不好看,对于用户体验其实是有很大的打折,因此这个效果确实是可以在实际工作中运用到的。
最后,如果这篇文章有帮助到你,❤️关注+点赞❤️鼓励一下作者,谢谢大家
本文正在参加「金石计划 . 瓜分6万现金大奖」
往期回顾
纯 CSS 实现 | 送你一杯热气腾腾的下午茶☕️,温暖你整个午后
暂无评论内容