配置enter键盘的光标移动
<el-form-item> <el-input v-enter-integer-number></el-input> </el-form-item> <el-form-item> <el-button v-enter-integer-number></el-button> </el-form-item> <el-form-item> <el-select placeholder="请选择活动区域" v-enter-integer-number filterable ></el-select> </el-form-item> <el-form-item> <el-button v-enter-integer-number></el-button> </el-form-item> <el-form-item> <el-input v-enter-integer-number></el-input> </el-form-item> <el-form-item> <el-input v-enter-integer-number></el-input> </el-form-item> <el-form-item> <el-input v-enter-integer-number></el-input> </el-form-item>
import Vue from 'vue'; Vue.directive('EnterIntegerNumber', { inserted: function (event) { event.addEventListener('keyup', function (e: any) { e = e || window.event; //没有这一句,无法使用e.keyCode const txts = document.getElementsByTagName('input'); //一个input标签的html集合 for (let i = 0; i < txts.length; i += 1) { const t: any = txts[i]; t.index = i; t.setAttribute('readonly', true); // t.preventDefault(); // 阻止事件的默认行为 t.onkeyup = function () { this.value = this.value.replace(/^(.).*$/, '$1'); const next = t.index < txts.length - 1 ? this.index + 1 : this.index; //最后一次删除时,光标停留在当前位置而不是前一,否则最后一个数字无法回退删除 const prev = t.index < 1 ? this.index : this.index - 1; //同理,避免第一个数字prev为-1 if (e.keyCode !== 8) { if (next > txts.length - 1) return next; txts[next].removeAttribute('readonly'); //只读 txts[next].focus(); } else { txts[prev].removeAttribute('readonly'); txts[prev].focus(); } }; txts[0].removeAttribute('readonly'); } }); } });