vue应用intersectionObserver达成上下选择文本定位

原创
小哥 3年前 (2022-11-14) 阅读数 37 #大杂烩

首先mounted中注册observer

注册快捷键已被跳过,只需放置被调用的函数。

        ...
        case types.ARROWUP:
          this.editIndex && this.handleArrowUpDown(up);
          break;
        case types.ARROWDOWN:
          // 如果只选择一行数据,则选择此文件
          (this.editIndex < length - 1 || length === 1) && this.handleArrowUpDown(down);
          break;
        ...
      handleArrowUpDown(type) {
      // this.actionType = type;
      // 如果只有一个文件或文件夹,请选择当前文件
      if (this.docInitList.length === 1) {
        this.tableRowClick(this.docInitList[0]);
        return;
      }
      if (this.editStatus) {
        this.doRename(this.docInitList[this.editIndex].docName);
        this.editStatus = false;
      }
      type === up ? (this.editIndex--, this.lastClickIndex--) : (this.editIndex++, this.lastClickIndex++);
      // 上部和下部选定文件跟踪位置
      this.scrollFileLocation();
      this.tableRowClick(this.docInitList[this.editIndex]);
    },

使用滚动条的位置。scrollIntoView的api
为了获取table中的每一行dom所以,得到全部table中的li 的 dom数组集合
然而,离开页面时,他不知道是上下键选择导致还是滚动条滚动,所以他注册了滚动条事件并将其更改为1。type

data() {
  rowObserver: ,
  // 表格中li->dom元素集合
  rowDomList: [],
  // 类型:键盘上下键或滚动条
   actionType: ,
  // 上次注册时间row observe dom信息
  lastRow: ,

}
mounted() {
  this.registerRowObserver();
},
methods: {
      queryAll() {
      ...
      // 每次重新查询整个页面时,都会对其进行修改。dom结构,因此重新获取dom节点
           // 根据新的dom获取新的dom列表
           this.rowDomList = Array.from(this.$refs.multipleTable.$el.getElementsByClassName(el-table__row));

      },
      registerRowObserver() {
      this.rowObserver = new IntersectionObserver((entries) => {
        console.log(entries, entries);
        console.log(ratio, entries[0].intersectionRatio);
        if (!entries[0].intersectionRatio > 0) {
          console.log(离开页面);

          const row = this.rowDomList[this.editIndex];
          // 向上跳到顶部,向下跳到底部
          switch (this.actionType) {
            case up:
              row.scrollIntoView(true);
              break;
            case down:
              row.scrollIntoView(false);
              break;
            default:
              break;
          }
        }
      });
      console.log(item, this.rowObserver);
    },
    // 方法通过observer判断窗口外的元素
    scrollFileLocation(type) {
      this.rowObserver.unobserve(this.lastRow);
      const row = this.rowDomList[this.editIndex];
      this.rowObserver.observe(row);
      this.lastRow = row;
    },
},
beforeDestroy() {
    this.rowObserver.disconnect();
    this.$refs.multipleTable.$el.removeEventListener(scroll, this.handleType, true);
}
版权声明

所有资源都来源于爬虫采集,如有侵权请联系我们,我们将立即删除

热门