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)

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

相关推荐
IT_陈寒2 分钟前
React 性能优化:5个实战技巧让首屏加载提升50%,开发者亲测有效!
前端·人工智能·后端
rising start19 分钟前
前端基础一、HTML5
前端·html·html5
鬼谷中妖28 分钟前
JavaScript 循环与对象:深入理解 for、for...in、for...of、不可枚举属性与可迭代对象
前端
大厂码农老A33 分钟前
你打的日志,正在拖垮你的系统:从P4小白到P7专家都是怎么打日志的?
java·前端·后端
im_AMBER35 分钟前
CSS 01【基础语法学习】
前端·css·笔记·学习
DokiDoki之父38 分钟前
前端速通—CSS篇
前端·css
pixle041 分钟前
Web大屏适配终极方案:vw/vh + flex + clamp() 完美组合
前端·大屏适配·vw/vh·clamp·终极方案·web大屏
ssf19871 小时前
前后端分离项目前端页面开发远程调试代理解决跨域问题方法
前端
@PHARAOH1 小时前
WHAT - 前端性能指标(加载性能指标)
前端
尘世中一位迷途小书童1 小时前
🎨 SCSS 高级用法完全指南:从入门到精通
前端·css·开源