Vue篇:el-table输入框实现方向建切换输入框聚焦

288 阅读1分钟

el-table输入框实现方向建切换输入框聚焦

首先这种处理最好是在全局进行公共实现,很多项目内部会对table进行二次封装,所以我们这里通过自定义指令实现

1、 实现思路:

  • 获取table下的所有输入框dom,监听keydow或keyup事件,对上下左右按钮进行处理
  • 鼠标按下时,计算需要聚焦的输入框,保证高亮行

话不多说代码如下

import Vue from 'vue'
Vue.directive('keyboard-focus', {
  bind(el) {
    el.addEventListener('keydown', (event) => {
      // 获取所有输入框
      const inputs = el.querySelectorAll('input')
      if (!inputs || inputs.length === 0) return

      // 获取当前焦点的输入框
      const activeElement = document.activeElement
      const currentIndex = Array.from(inputs).indexOf(activeElement)
      if (currentIndex === -1) return

      // 获取表格的总列数
      const firstRowInputs = el.querySelectorAll('tr:first-child input')
      const totalColumns = firstRowInputs.length

      // 计算目标索引
      let nextIndex = currentIndex
      let nextRow = null
      switch (event.key) {
        case 'ArrowUp':
          if (currentIndex >= totalColumns) {
            nextIndex = currentIndex - totalColumns
            nextRow = inputs[nextIndex].closest('tr') // 获取目标行
          }
          break
        case 'ArrowDown':
          if (currentIndex < inputs.length - totalColumns) {
            nextIndex = currentIndex + totalColumns
            nextRow = inputs[nextIndex].closest('tr') // 获取目标行
          }
          break
        case 'ArrowLeft':
          // 判断是否为当前行的第一列
          if (currentIndex % totalColumns !== 0) {
            nextIndex = currentIndex - 1
          }
          break
        case 'ArrowRight':
          // 判断是否为当前行的最后一列
          if ((currentIndex + 1) % totalColumns !== 0) {
            nextIndex = currentIndex + 1
          }
          break
        default:
          return // 非方向键不处理
      }

      // 切换焦点
      if (nextIndex >= 0 && nextIndex < inputs.length) {
        const nextInput = inputs[nextIndex]
        nextInput.focus()

        // 获取当前行
        const currentRow = activeElement.closest('tr')

        // 如果是上下方向键,切换行高亮
        if (nextRow && (event.key === 'ArrowUp' || event.key === 'ArrowDown')) {
          // 移除当前高亮行的类
          if (currentRow) {
            currentRow.classList.remove('current-row')
          }

          // 给目标行添加高亮类
          nextRow.classList.add('current-row')
        }

        event.preventDefault() // 阻止默认行为
      }
    })
  }
})
    import './utils/tableFocus.js' // 支持el-table方向键聚焦

最后直接绑定自定义指令即可

image.png