vue+element-ui 实现table单元格点击编辑,并且按上下键移动

1.接到需求是点击键盘上下键,控制输入框移动方便输入数据
vue+element-ui 实现table单元格点击编辑,并且按上下键移动_第1张图片
2.相关实现代码

<el-table-column label="档距(m)" prop="span" width="120" align="center">
   <template slot-scope="scope">
     <el-input size="mini"  placeholder="请填写值"
     :value="scope.row.span"
     @input="handlerNumberChange($event,scope.row)"
     @click.native="handleNative"
    />
   </template>
 </el-table-column>
 
 //==============
 handleNative(){
      const len = this.list.length ;
      document.onkeydown = (v)=>{
        if (document.activeElement.nodeName.toLocaleLowerCase() !== "input") {
          return document.onkeydown = null;
        }
        let curel = document.activeElement ; //文档中当前获得焦点的元素
        while(curel.nodeName.toLocaleLowerCase() !== "td" &&  curel.nodeName.toLocaleLowerCase() !== "body") {
            curel = curel.parentElement
        }
        if (curel.nodeName.toLocaleLowerCase() === "body") {
          return  document.onkeydown = null;
        }
        const curcellIndex = curel.cellIndex; // 当前元素列单元格索引
        // 当前所在table(this.list) 的行的index : sectionRowIndex 
        let index = curel.parentElement.sectionRowIndex ;
        let curtbody = curel.parentElement; //当前tbody内容的整个表单
        while(curtbody.nodeName.toLocaleLowerCase() !== "tbody") {
            curtbody = curtbody.parentElement
        }

        const rowItem = i => curtbody.children[i].children[curcellIndex] ;
        // 13 enter| 40 下 |  38 上
        let flag = false;
        if (v.keyCode === 40 || v.keyCode === 38) {
          flag = true
          this.oldInputNode = rowItem(index).getElementsByTagName('input')[0];
          this.oldRow = this.list[index] ;
        }
        
        if (v.keyCode === 40) {
            index += 1;
          if (index === len) {  index = 0  } 
        }
        if (v.keyCode === 38) {
          index -= 1
          if (index < 0 ) {  index = len - 1 } 
        }
        if (flag) {
          const inputNode = rowItem(index).getElementsByTagName('input')[0] ;
          if (inputNode.dataset.disabled) {
            this.oldInputNode && this.oldInputNode.blur()
          }else{
            inputNode.focus() ;
          }
          this.$refs.table.setCurrentRow(this.list[index]) ;
        }  
      }
    },

参考:https://www.cnblogs.com/Tohold/p/9559092.html

你可能感兴趣的:(学习笔记,javascript,vue.js,es6)