基于el-table组件实现高度自定义后数据自动滚动效果的指令

符棋
2023-12-01

         运用方式:直接在el-table组件上加上v-auto-scroll指令即可,就可实现数据超时,自动进行轮播效果。

        代码实现如下:

let timer = null;
let scrollBlockX = 0; // 滚动条位置;
let moveDir =  1// 移动发现 1 正向  -1  方向
// 移动的距离
let scrollTop = 0;


// 设置表格数据自动滚动
function dataScroll(el){
  clearTimeout(timer);
  timer = setTimeout(() => {
    dataScroll(el);
  }, 50);
  let oTable = el.querySelectorAll(".el-table__body-wrapper")[0];
  scrollBlockX += moveDir;

  oTable.scrollTo(0, scrollBlockX);
  // 判断是否触底
  if(scrollTop == oTable.scrollTop){
    moveDir *= -1;
    scrollTop = scrollTop + 100;
  }else{
    scrollTop = oTable.scrollTop;
  }
}
function init(el){
  clearTimeout(timer);
  scrollBlockX = 0;
  moveDir = 1;
  scrollTop = 0;
  el && el.querySelectorAll(".el-table__body-wrapper")[0].scrollTo(0,0)
}
Vue.directive('auto-scroll',{
  bind(el) {
    init(el);
  },
  inserted() {
  },
  update() {
  },
  async componentUpdated(el, bind, vNode, oldVNode) {
    // console.log("enter", el, bind, vNode, oldVNode);
    init(el);
    await new Promise(resolve => setTimeout(() => resolve(), 200));
    if (!Array.from(el.classList).includes("el-table--scrollable-y")) return false;
      dataScroll(el);
    let oTable = el.querySelectorAll(".el-table__body-wrapper")[0];
    oTable.addEventListener('mouseenter',() => {
      clearTimeout(timer);
    })
    oTable.addEventListener('mouseleave',() => {
      clearTimeout(timer);
      let oTable = el.querySelectorAll(".el-table__body-wrapper")[0];
      scrollBlockX =  oTable.scrollTop - moveDir
      scrollTop = oTable.scrollTop
      dataScroll(el);
    })
  },
  unbind() {
    clearTimeout(timer);
  },
 }
)

 类似资料: