实现一个4位验证码输入框
本栏目所有章节源码已同步Gitee
首先见效果图:
总共分为HTML、CSS、Javascript三个部分
一、HTML部分
布局上我们使用4个div
元素作为显示验证码的盒子,除此之外,使用一个input
元素作为数值的输入,但是input
是不可见的切可输入的(opacity设置为0)
。
HTML代码如下:
<div class="title">验证码输入框</div>
<!-- 验证码输入框-案例***如果你有更好的实现方案-可以到我的此篇文章下交流哦! -->
<!-- 结构 -->
<div class="code-box">
<!-- 该部分展示给用户- ---使用flex布局 -->
<div class="code-item"></div>
<div class="code-item"></div>
<div class="code-item"></div>
<div class="code-item"></div>
<!-- 该输入框需要隐藏 -->
<input type="text" class="code-input" maxlength="4">
</div>
二、CSS部分
4个验证码盒子主要使用到flex布局
,并且大盒子code-box
设置为position:relative
,因为我们需要让input
显示在上层,确保他能被点击到,所以给input
设置position:absolute
并且让它不显示-opacity设置为0
;
除此之外,我们需要定义一个active
的样式,来让当前激活
的验证码输入框有特殊的样式
CSS代码如下:
* {
padding: 0;
margin: 0;
}
body {
background-color: #fff;
}
.title {
width: 100%;
text-align: center;
height: 40px;
line-height: 40px;
background-color: #1E80FF;
color: #fff;
letter-spacing: 1px;
font-size: 16px
}
.code-box {
display: flex;
justify-content: space-between;
width: 230px;
margin: 80px auto;
position: relative;
}
.code-box .code-item {
width: 50px;
height: 50px;
background-color: #fff;
border-radius: 5px 5px;
text-align: center;
line-height: 50px;
font-size: 24px;
color: #000;
font-weight: bold;
border: 1px solid rgb(209, 209, 209);
transition: border 0.3s;
box-sizing: border-box;
}
.code-box .code-input {
position: absolute;
width: 100%;
height: 100%;
opacity: 0;
}
.active {
border: 3px solid #1E80FF !important;
}
三、Javascript部分
- 我们需要获取到所有的验证码盒子的DOM元素以及input DOM元素
- 定义一个函数
showNum
,将输入框中的值转为数组后,循环显示到对应的验证码输入框中 - 定义一个函数
cutAct
,进行清除之前的激活样式并且计算并激活当前的验证码框的样式,除此之外我们还处理了当input
分别为focus
和blur
状态下,激活样式的处理。
Javascript代码如下:
window.addEventListener('load', () => {
// 获取元素
const codeItem = document.querySelectorAll('.code-item')
const codeInput = document.querySelector('.code-input')
// 循环显示input中的值到code-item中
const showNum = () => {
// 获取到当前input的值
const curVal = codeInput.value
// 循环显示到code-item中
Array.from(codeItem).map((item, index) => {
curVal[index] ?
item.innerText = curVal[index] :
item.innerText = ''
})
}
// 处理active类的增删
const cutAct = (type) => {
// 获取当前input中值的长度
const valLenth = codeInput.value.length
// 首先清除之前的active类名
Array.from(codeItem).map(item => {
item.className = 'code-item'
})
// 当type为focus时 进行计算active位置 否则只清除
if (type === 'focus') {
// 计算出当前应该active的code-item 并且给他添加active类名
// 因为input的值有4个长度,他的长度是从1开始的;
// 而codeItem位数组,下标为0,从0开始的,所以当input长度为4时,对应的codeItem其实是不存在的 所以我们需要减一
codeItem[valLenth === 4 ? valLenth - 1 : valLenth].className = 'code-item active'
}
}
// 为输入框添加事件
codeInput.addEventListener('focus', () => {
// 聚焦时 计算active的code-item
cutAct('focus')
})
codeInput.addEventListener('blur', () => {
// 失去焦点时 移除当前的active
cutAct('blur')
})
codeInput.addEventListener('input', () => {
// 当输入值时,调用循环显示函数
showNum()
cutAct('focus')
})
})