遇到一个需求,需要实现和移动端短信输入一样,输入内容后,光标会进入下一个输入框
需要用到2个事件
keydown事件发生在键盘的键被按下的时候
keyup 事件在按键被释放的时候触发
<template><div class="box"><el-form :model="ruleForm" :rules="rules" ref="ruleForm" class="demo-ruleForm"><el-form-item label="名称" prop="name"><span v-for="(item,index) in namelist" :key="index"><input v-model="item.val" class="border-input" @keyup="nextFocus($event,index)" @keydown="changeValue(index)" /></span></el-form-item></el-form></div>
</template><script>
export default {data () {return {ruleForm: {name: ''},namelist: [{ val: '' },{ val: '' },{ val: '' }],rules: {name: [{ required: true, message: '请输入活动名称', trigger: 'blur' }],}}},methods: {/*对焦到下一个input框去*/nextFocus (el, index) {var dom = document.getElementsByClassName("border-input"),currInput = dom[index],nextInput = dom[index + 1],lastInput = dom[index - 1];// 删除键if (el.keyCode != 8) {if (index < (this.namelist.length - 1)) {nextInput.focus();} else {currInput.blur();}} else {if (index != 0) {lastInput.focus();}}// 进行赋值this.ruleForm.name = this.namelist.map(item => item.val).join('')},/*当键盘按下的时候清空原有的数*/changeValue (index) {this.namelist[index].val = "";}}
}
</script><style lang="less" scoped>
.border-input {background: #ffffff;width: 24px;font-size: 24px;height: 24px;margin-left: 8px;text-align: center;border: 1px solid #ccc;border-radius: 4px;
}
.box {width: 400px;margin: 0 auto;border: 1px solid #ccc;
}
/deep/.el-form-item__content {text-align: right;
}
</style>