vue ip输入框

由这位大佬的分享修改而来(https://www.jianshu.com/p/40c874f111fc)

因为本人将其用在移动端,所以使用键盘左右键有点bug,又因本人实力有限,所以没有修改*

HTML 代码部分

<template>
  <ul class="ipAdress">
    <li v-for="(item,index) in ipAdress" :key="index">
      <input
        type="text"
        @input="checkIpVal(item,index)"
        @keyup="turnIpPOS(item,index,$event)"
        v-model="item.value"
        ref="ipInput"
      />
      <div></div>
    </li>
  </ul>
</template>

CSS 代码部分 此处为了方便自己使用,我修改了长度

<style scoped>
.ipAdress {
  display: flex;
  align-items: center;
  border: 1px solid #0190fe;
  width: 95%;
  margin-right: 10px;
}
.ipAdress li {
  position: relative;
  height: 23px;
  margin: 0;
}
ul[class="ipAdress"] input[type="text"] {
  border: none;
  width: 100%;
  height: 23px;
  text-align: center;
  background: transparent;
  color: #efefef;
}
.ipAdress li div {
  position: absolute;
  bottom: 2px;
  right: 0;
  border-radius: 50%;
  background: #0190fe;
  width: 2px;
  height: 2px;
}
/*只需要3个div*/
.ipAdress li:last-child div {
  display: none;
}
/*取消掉默认的input focus状态*/
.ipAdress input:focus {
  outline: none;
}
</style>

JS* 代码部分 此处修改了删除换框的方式,修改了输入框满框后换框的方式

<script>
export default {
  data() {
    return {
      ipAdress: [
        {
          value: ""
        },
        {
          value: ""
        },
        {
          value: ""
        },
        {
          value: ""
        }
      ]
    };
  },
  methods: {
    checkIpVal(item, index) {
      //输入时事件
      // let self = this;
      //确保每个值都处于0-255
      let self = this;
      let val = item.value;
      //当输入的是空格时,值赋为空
      val = val.trim();
      val = parseInt(val, 10);
      if (isNaN(val)) {
        val = "";
      } else {
        val = val < 0 ? "" : val;
        val = val > 255 ? 255 : val;
      }
      item.value = val;
      console.log(val);
      if (val > 99 && index < this.ipAdress.length - 1) {
        //判断内容是否可以跳框
        self.$refs.ipInput[index + 1].focus();
      }
      if (val == "" &&index !=0) {
        self.$refs.ipInput[index - 1].focus();
      }
    },
    turnIpPOS(item, index, event) {
      let self = this;
      let e = event || window.event;
      //左箭头向左跳转,左一不做任何措施
      if (e.keyCode == 37) {
        if (index == 0) {
          1 == 1;
        } else {
          console.log(index);

          self.$refs.ipInput[index - 1].focus();
        }
      }
      //右箭头、回车键、空格键、冒号均向右跳转,右一不做任何措施
      if (
        e.keyCode == 39 ||
        e.keyCode == 13 ||
        e.keyCode == 32 ||
        e.keyCode == 190
      ) {
        if (index == 3) {
          1 == 1;
        } else {
          console.log(index);
          self.$refs.ipInput[index + 1].focus();
        }
      }
    }
  }
};
</script>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值