el-table中实现可选表格区域的鼠标事件检测

背景描述

  • vue3+element plus
  • 想要实现el-table中特定区域内的单元格才可点击

代码实现

  • 首先,需要给el-table绑定单元格点击事件
typescript 复制代码
<el-table 
    :data="currTableData"
    border
    style="width: 100%;"
    height="calc(100vh - 400px)"
    @cell-click="handleCellClick"
>
...
  • 在handleCellClick()方法中,调用鼠标事件检测的方法
typescript 复制代码
// 判断鼠标是否在可选区域内
const isInSelectableArea = event => {
   const target = event.target
   // 查找最近的表头元素(th或thead)
   const headerElement = target.closest('th, thead')

   // 如果目标元素位于表头中,返回false
   if (headerElement) return false

   const headerSelect = document.querySelector('.table-con')
   if (!headerSelect) return false

   const headerRect = headerSelect.getBoundingClientRect()
   const isInHeader = 
       event.clientX >= headerRect.left &&
       event.clientX <= headerRect.right &&
       event.clientY >= headerRect.top &&
       event.clientY <= headerRect.bottom;
   
   const cell = target.closest('td, th')
   const columnIndex = cell ? cell.cellIndex : undefined;

   return isInHeader && columnIndex > 2; // 从第四列开始,这里根据需求修改,我是前三列不准点击
}
  • 注意,这里作为参数的event,来自handleCellClick(row, column, cell, event)

这里方法的逻辑总体还是比较简单的,不过因为属于通用性比较强的方法,所以记录一下。

相关推荐
mCell1 天前
GSAP ScrollTrigger 详解
前端·javascript·动效
gnip1 天前
Node.js 子进程:child_process
前端·javascript
excel1 天前
为什么在 Three.js 中平面能产生“起伏效果”?
前端
excel1 天前
Node.js 断言与测试框架示例对比
前端
天蓝色的鱼鱼1 天前
前端开发者的组件设计之痛:为什么我的组件总是难以维护?
前端·react.js
codingandsleeping1 天前
使用orval自动拉取swagger文档并生成ts接口
前端·javascript
石金龙1 天前
[译] Composition in CSS
前端·css
白水清风1 天前
微前端学习记录(qiankun、wujie、micro-app)
前端·javascript·前端工程化
Ticnix1 天前
函数封装实现Echarts多表渲染/叠加渲染
前端·echarts
用户22152044278001 天前
new、原型和原型链浅析
前端·javascript