其他分享
首页 > 其他分享> > 创建一个web端的支付密码输入框

创建一个web端的支付密码输入框

作者:互联网

效果图在这里插入图片描述

在这里插入图片描述

直接上代码
直接封装成一个组件,哪里需要就直接调用就可以了

<template>
  <div class="am-payPwd" :id="`ids_${id}`">
    <input
      type="password"
      readonly
      onfocus="this.removeAttribute('readonly');"
      maxlength="1"
      autocomplete="new-password"
      @input="changeInput"
      @click="changePwd"
      v-model="pwdList[i]"
      @keyup="keyUp($event)"
      @keydown="oldPwdList = pwdList.length"
      class="shortInput"
      v-for="(v, i) in 6"
      :key="i"
    />
  </div>
</template>
<script>
export default {
  data() {
    return {
      pwdList: [],
      oldPwdList: [],
      isDelete: false,
      ipt: "",
      active: -1,
    };
  },
  props: {
    id: {
      type: Number,
      default: 1, // 当一个页面有多个密码输入框时,用id来区分
    },
  },
  mounted() {
    this.ipt = document.querySelectorAll(`#ids_${this.id} .shortInput`);
  },
  methods: {
    keyUp(ev) {
  
      let index = this.pwdList.length;
      this.active = index;

      if (!index) return;
      if (ev.keyCode === 8) {
        this.isDelete = true;
        if (this.oldPwdList === this.pwdList.length) {
          if (index === this.pwdList.length) {
            this.pwdList.pop();
          }
          index--;
        } else {
          index > 0 && index--;
        }
        this.ipt[index].focus();
      } else if (
        this.isDelete &&
        index === this.pwdList.length &&
        /^\d$/.test(ev.key)
      ) {
        this.isDelete = false;
        this.pwdList.pop();
        this.pwdList.push(ev.key);
        this.ipt[this.pwdList.length] && this.ipt[this.pwdList.length].focus();
        
      }
    //   this.$emit("getPwd", this.pwdList.join(""));//给父组件传递数据
       console.log(this.pwdList.join(""));
    },
    changePwd() {
        console.log('11');
      let index = this.pwdList.length;
      index === 6 && index--;
      this.ipt[index].focus();
    },
    changeInput() {
        
      let index = this.pwdList.length;
      let val = this.pwdList[index - 1];
      if (!/[0-9]/.test(val)) {
        this.pwdList.pop();
        return;
      }
      if (!val) {
        this.pwdList.pop();
        index--;
        console.log(this.ipt);
        if (index > 0) this.ipt[index - 1].focus();
      } else {
        if (index < 6) this.ipt[index].focus();
      }
    },
  },
};
</script>
<style lang="less" >
.am-payPwd {
  width: 242px;
  border: 1px solid #c5c5c5;
  line-height: 40px;
  height: 40px;
  border-radius: 5px;
  .shortInput {
    width: 40px;
    height: 20px;
    padding: 10px 0;
    border: 0px;
    border-right: 1px solid #c5c5c5;

    color: #333;
    text-align: center;
    outline: #ff0067;
    &:last-child {
      border-right: 0px solid #c5c5c5;
    }
  }
  input {
    color: transparent;
  }
}
</style>

标签:web,&&,index,端的,focus,输入框,length,ipt,pwdList
来源: https://blog.csdn.net/weixin_52005030/article/details/119275648