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)

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

相关推荐
LaughingZhu23 分钟前
PH热榜 | 2025-04-26
前端·数据库·人工智能·mysql·开源
萌萌哒草头将军6 小时前
⚡⚡⚡尤雨溪宣布开发 Vite Devtools,这两个很哇塞 🚀 Vite 的插件,你一定要知道!
前端·vue.js·vite
小彭努力中7 小时前
7.Three.js 中 CubeCamera详解与实战示例
开发语言·前端·javascript·vue.js·ecmascript
浪裡遊8 小时前
跨域问题(Cross-Origin Problem)
linux·前端·vue.js·后端·https·sprint
滿8 小时前
Vue3 Element Plus el-tabs数据刷新方法
javascript·vue.js·elementui
LinDaiuuj8 小时前
判断符号??,?. ,! ,!! ,|| ,&&,?: 意思以及举例
开发语言·前端·javascript
敲厉害的燕宝8 小时前
Pinia——Vue的Store状态管理库
前端·javascript·vue.js
Aphasia3118 小时前
react必备JavaScript知识点(二)——类
前端·javascript
玖玖passion8 小时前
数组转树:数据结构中的经典问题
前端
呼Lu噜8 小时前
WPF-遵循MVVM框架创建图表的显示【保姆级】
前端·后端·wpf