验证码
通过html、css、js实现验证码的输入
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>验证码输入</title>
<style>
.div {
width: fit-content;
height: fit-content;
background-color: red;
}
.div1 {
width: 300px;
height: 300px;
}
@keyframes divmove {
from {
width: 0;
height: 0;
background-color: #000;
}
to {
width: 100%;
height: 100%;
background-color: #fff;
}
}
.input-wrap {
width: 100%;
height: 100%;
display: flex;
align-items: center;
justify-content: center;
position: relative;
}
.visible {
position: absolute;
top: 0;
left: 100px;
width: 600px;
height: 50px;
opacity: 0;
z-index: 2;
}
.input-content {
position: absolute;
top: 0;
left: 100px;
width: 600px;
height: 50px;
display: flex;
align-content: center;
justify-content: space-between;
}
.input-item {
width: 50px;
height: 50px;
border: 1px solid #000;
margin: 0;
position: relative;
display: flex;
align-items: center;
justify-content: center;
}
.active::after {
content: '';
position: absolute;
width: 1px;
height: 30px;
left: 24.5px;
top: 10px;
background-color: #000;
animation: lightcursor 1.5s .5s infinite;
}
@keyframes lightcursor {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
</style>
</head>
<body>
<div class="input-wrap">
<input type="text" class="visible" />
<div class="input-content">
<p class="input-item"></p>
<p class="input-item"></p>
<p class="input-item"></p>
<p class="input-item"></p>
<p class="input-item"></p>
<p class="input-item"></p>
</div>
</div>
<script>
const oInput = document.querySelector('.visible');
const items = document.querySelectorAll('.input-item');
const reg = /^[0-9]{0,6}$/;
let prevVal;
oInput.addEventListener('focus', (e) => {
const val = oInput.value;
if (!val) {
items[0].classList.add('active');
return false;
}
if (val.length < items.length) {
items[val.length].classList.add('active');
return false;
}
if (val.length == items.length) {
items[val.length - 1].classList.add('active');
return false;
}
});
oInput.addEventListener('blur', (e) => {
items.forEach(item => {
item.classList.remove('active');
});
});
oInput.addEventListener('input', (e) => {
const val = e.target.value;
if (reg.test(val)) {
prevVal = val;
} else {
oInput.value = prevVal;
}
const arr = oInput.value.split('');
if (!arr.length) {
return false;
}
arr.forEach((item, idx) => {
items[idx].textContent = item;
items[idx].classList.remove('active');
if (items[idx + 1]) {
items[idx + 1].classList.add('active');
}
if (idx == items.length - 1) {
items[idx].classList.remove('active');
}
})
});
</script>
</body>
</html>