上下左右按键input聚焦
### html 使用 在需要聚焦的input后加下面内容 @keydown.native="handleKeyDown($event, 0, 0)" :ref="'0_0'" 或者 @keydown.native="handleKeyDown($event, index, 0)" :ref="`${index}_0`" ### 引入此方法 handleKeyDown (event, rowIndex, colIndex) { const maxArr = [5, 5]; // 每一行最多有多少可聚焦输入框(从0开始) const refKey = handleKeyDown(event, rowIndex, colIndex, maxArr); if (this.$refs[refKey]) { this.$refs[refKey].focus(); } } #### 数组遍历情况使用 if (this.$refs[refKey][0]) { this.$refs[refKey][0].focus(); } #### 左侧为rowspan时需拆分字符串 // 通过_拆分字符串 const arr = refKey.split("_"); if (arr[0] >= 6) { if ((arr[0] > 6) && arr[1] == 0) { this.handleKeyDown(event, arr[0], arr[1]); return; }; if (this.$refs[refKey][0]) { this.$refs[refKey][0].focus(); } } else if (this.$refs[refKey]) { this.$refs[refKey].focus(); }
utils
// 监听上下左右 export function handleKeyDown(event, rowIndex, colIndex, maxArr) { const keyCode = event.keyCode; // 阻止方向键左右的默认行为 if ([37, , 38, 39, 40].includes(event.keyCode)) { event.preventDefault(); } let nextRow = rowIndex; let nextColumn = colIndex; const maxRow = maxArr.length; const maxCol = maxArr[rowIndex]; switch (keyCode) { case 37: // left if (colIndex > 0) nextColumn--; // 当col为0 row大于0时,取row-1,col最大值 if (colIndex == 0 && rowIndex > 0) { nextRow--; nextColumn = maxArr[nextRow]; } break; case 39: // right if (colIndex < maxCol) nextColumn++; // 当col等于最大值,row小于最大行时,取row+1,col为0 if (colIndex == maxCol && rowIndex < maxRow) { nextRow++; nextColumn = 0; } break; case 38: // up if (rowIndex > 0) nextRow--; // 当前col大于将要聚焦的那一行的col最大值时,取新行最大值 if (nextColumn > maxArr[nextRow]) { nextColumn = maxArr[nextRow]; } break; case 40: // down if (rowIndex < maxRow) nextRow++; // 当前col大于将要聚焦的那一行的col最大值时,取新行最大值 if (nextColumn > maxArr[nextRow]) { nextColumn = maxArr[nextRow]; } break; } return `${nextRow}_${nextColumn}`; }
标签:rowIndex,refKey,excel,nextRow,nextColumn,跳转,input,maxArr,event From: https://www.cnblogs.com/wjian0916/p/18428399