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)

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

相关推荐
大怪v4 小时前
AI抢饭?前端佬:我要验牌!
前端·人工智能·程序员
新酱爱学习4 小时前
字节外包一年,我的技术成长之路
前端·程序员·年终总结
小兵张健4 小时前
开源 playwright-pool 会话池来了
前端·javascript·github
IT_陈寒7 小时前
Python开发者必知的5大性能陷阱:90%的人都踩过的坑!
前端·人工智能·后端
codingWhat7 小时前
介绍一个手势识别库——AlloyFinger
前端·javascript·vue.js
代码老中医7 小时前
2026年CSS彻底疯了:这6个新特性让我删掉了三分之一JS代码
前端
不会敲代码17 小时前
Zustand:轻量级状态管理,从入门到实践
前端·typescript
踩着两条虫7 小时前
VTJ.PRO 双向代码转换原理揭秘
前端·vue.js·人工智能
扉川川7 小时前
OpenClaw 架构解析:一个生产级 AI Agent 是如何设计的
前端·人工智能
远山枫谷8 小时前
一文理清页面/组件通信与 Store 全局状态管理
前端·微信小程序