验证码输入(6个方格)、可自动聚焦下一个、输入长度达到6位数触发相关处理逻辑

想不想要验证码方格的实现效果?   回答:想~哈哈哈

应用场景:方格验证码输入,这里用的框架是iView的输入框,大家可自行改为自己项目框架的输入框标签!

实现思路:循环多个输入框,将输入框样式修改为合适大小的正方形,在@input里进行相关逻辑处理。

<div class="verification-code-input">
   <Input v-for="(item, index) in codeLength" :key="index" class="code-input-item" maxlength="1" @input="(event) => handleInput(event, index)" ref="codeInput" />
</div>

CSS:样式设置为适合自己的方格 

.verification-code-input {
   display: flex;
   justify-content: space-between;
   margin-top: 34px;

   /deep/.ivu-input {
     width: 74px;
     height: 74px;
     font-size: 32px;
     font-weight: bold;
     padding: 27px;
   }

   .code-input-item {
     max-width: 100%;
     margin: 0;
     padding: 0;
     text-align: center;
   }
 }

Data中定义相关变量: 


  data() {
    return {
      oathCode: '',
      codeLength: 6, // 设置验证码的长度
    }
  }

JS:这里处理输入框的自动聚焦到下一个,输入框输入、输出的逻辑等

methods: {
    handleInput(event, index) {
      let inputValue = event;
      if (inputValue) {
        // 如果是正常输入
        if (this.oathCode.length === index) {
          if (this.oathCode.length < this.codeLength && index + 1 < this.$refs.codeInput.length) {
            this.$refs.codeInput[index + 1].focus();
          }
          this.oathCode += inputValue;
        } else {
          if (this.oathCode.length < this.codeLength && index + 1 < this.$refs.codeInput.length) {
            this.$refs.codeInput[index + 1].focus();
          }
          this.$refs.codeInput[index + 1].focus();
          // 如果是修改操作
          this.oathCode = this.oathCode.slice(0, index) + inputValue + this.oathCode.slice(index + 1);
        }
      } else {
        if (this.oathCode.length > index && index > 0) {
          this.oathCode = this.oathCode.slice(0, index) + this.oathCode.slice(index + 1);
          this.$nextTick(() => {
            if (this.$refs.codeInput[index - 1]) {
              this.$refs.codeInput[index - 1].focus();
            }
          });
        }
      }
      this.form.currencyCode = this.userCurrency.code;
      this.form.emailCode = this.oathCode;
      if (this.oathCode.length === this.codeLength) {
        //这里是判断输入验证码为6位数完成之后的操作,例如注册、登录逻辑处理
      }
    },
}

附带视频效果,欢迎大家来交流,哇哈哈哈......

验证码输入框效果视频

  • 4
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值