uni-app h5 验证码变为六个输入框
时间: 2025-02-22 18:41:11 浏览: 108
要在uni-app H5项目中将验证码显示为六个独立的输入框,你可以通过自定义样式和使用`<view>`组件结合`<input>`标签来实现这一功能。下面是一个简单的示例:
### HTML结构
```html
<!-- 使用 view 包裹 input 来创建单个字符输入框 -->
<template>
<view class="verify-code-container">
<!-- 循环渲染6个输入框 -->
<view v-for="(item, index) in codeLength" :key="index" class="code-input-wrap">
<input type="text"
maxlength="1"
@input="handleInput(index)"
:focus="currentIndex === index"
class="single-code-box"/>
</view>
</view>
</template>
```
- `v-for`: 这里用于循环生成指定数量(本案例为6个)的输入框。
- `maxlength="1"`: 每个输入框只允许用户输入一个字符。
### JavaScript部分
```javascript
<script setup lang="ts">
import { ref } from 'vue';
const currentIndex = ref(-1); // 当前聚焦的位置索引
let currentCodeValue = ''; // 存储完整的验证码值
// 输入处理函数
function handleInput(index:number){
const value=event.target.value;
if (value !== '') {
currentCodeValue += value; // 将当前字符加入到完整验证码字符串
// 移动焦点至下一个输入框
if(currentIndex.value < 4){
currentIndex.value=index + 1;
if (currentIndex.value >= 5 && currentCodeValue.length===6){
console.log("The complete verification code is:",currentCodeValue);
// 完成验证逻辑...
clearInputs(); // 清空所有输入框以便下一次尝试
}
}
} else{
// 如果删除了内容则回退到上一格
if (index > 0){
currentIndex.value--;
}
currentCodeValue=currentCodeValue.slice(0,-1);
}
}
//清除所有的输入框及存储的数据
function clearInputs(){
currentCodeValue='';
currentIndex.value=-1;
}
</script>
```
这里我们监听每个输入框的变化,并在用户完成每一步操作之后自动切换光标位置直到整个验证码填写完毕为止;当达到最大长度时还可以触发额外的操作比如提交表单等。
### CSS美化
为了增强用户体验感,可以添加一些基础样式的调整让这组输入框看起来更美观:
```css
<style scoped>
.verify-code-container {
display: flex;
justify-content: center;
margin-top: 20px;
}
.code-input-wrap {
position:relative;
width:36px;height:36px;line-height:36px;text-align:center;margin-right:8px;border-bottom:solid 1px #ccc;font-size:.7rem;color:#aaa;}
.single-code-box{width:inherit;height:inherit;padding:0;-webkit-appearance:none;background-color:transparent;border-radius:0 none;border-style:none;text-align:center;} /* 去除默认边框 */
/* 其它需要应用的效果可继续补充 */
</style>
```
这种设计让用户每次只能在一个小方块内键入单一数字或字母,同时实现了视觉分离效果,提高了易读性和交互友好度。
---
阅读全文
相关推荐


















