报表中按下上下左右按键input会像excel一样跳转聚焦

上下左右按键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}`;
}
复制代码

 

posted @   请叫我王小胖  阅读(27)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
点击右上角即可分享
微信分享提示
主题色彩