本篇内容主要讲解“vue输入框怎么实现输完后光标自动跳到下一个输入框中”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“vue输入框怎么实现输完后光标自动跳到下一个输入框中”吧!
实现思路
首先我们需要通过
keyup()事件在用户输入完字符后,利用
document.getElementsByClassName方法获取到输入框的
dom元素集合,拿到当前元素的
key和
index值,通过判断确定光标是否跳到下一个输入框(
focus)还是光标失焦(
blur);
keydown()事件主要就是为了防止一旦输入过快,一个输入框中会有多个字符的问题。 本章用到的属性以及方法如下:
focus()
focus()当元素获得焦点时(当通过鼠标点击选中元素或通过
tab键定位到元素时),发生
focus事件。
focus()方法触发
focus事件,或规定当发生
focus事件时运行的函数。
blur()
当元素失去焦点时发生
blur事件。
blur()方法触发
blur事件,或规定当发生
blur事件时运行的函数。
keyup()
keyup()方法触发
keyup事件,或规定当发生
keyup事件时运行的函数。
keydown()
当键盘键被按下时触发
keydown事件。需要注意的是
keydown()是在键盘按下触发,而
keyup()是在键盘松手就会触发。
document.getElementsByClassName()
getElementsByClassName()方法返回文档中所有指定类名的元素集合,作为
NodeList对象。
NodeList对象代表一个有顺序的节点列表。
NodeList对象 我们可通过节点列表中的节点索引号来访问列表中的节点(索引号由0开始)。
完整源码
<template>
<div class="parentBox">
<div v-for="(item, index) in inputList" :key="index">
<input type="text" v-model="item.pinless" class="inputValue" @keyup="keyboard($event, index)" @keydown="expurgate(index)" />
</div>
</div>
</template>
<script>
export default {
data() {
return {
// 输入框循环的数组
inputList: [
{ pinless: "" },
{ pinless: "" },
{ pinless: "" },
{ pinless: "" },
{ pinless: "" },
{ pinless: "" },
],
};
},
methods: {
// 键盘松开事件
keyboard(e, index) {
let domNode = document.getElementsByClassName("inputValue"),
currInput = domNode[index],
nextInput = domNode[index + 1],
lastInput = domNode[index - 1];
if (e.keyCode != 8) {
if (index < this.inputList.length - 1) {
nextInput.focus();
} else {
currInput.blur();
}
} else {
if (index != 0) {
lastInput.focus();
}
}
},
// 键盘按下触发
expurgate(index) {
this.inputList[index].pinless = "";
},
},
};
</script>
<style scoped>
.parentBox {
padding: 20px;
display: flex;
}
.parentBox div:nth-child(n + 2) {
margin-left: 4px;
}
input {
color: #606266;
font-size: 18px;
text-align: center;
width: 54px;
height: 62px;
border: 2px solid gainsboro;
border-radius: 4px;
}
</style>实现效果