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)

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

相关推荐
先做个垃圾出来………1 分钟前
split方法
前端
前端Hardy35 分钟前
HTML&CSS:3D图片切换效果
前端·javascript
spionbo1 小时前
Vue 表情包输入组件实现代码及完整开发流程解析
前端·javascript·面试
全宝1 小时前
✏️Canvas实现环形文字
前端·javascript·canvas
lyc2333331 小时前
鸿蒙Core File Kit:极简文件管理指南📁
前端
我这里是好的呀1 小时前
全栈开发个人博客12.嵌套评论设计
前端·全栈
我这里是好的呀1 小时前
全栈开发个人博客13.AI聊天设计
前端·全栈
金金金__1 小时前
Element-Plus:popconfirm与tooltip一起使用不生效?
前端·vue.js·element
lyc2333331 小时前
小L带你看鸿蒙应用升级的数据迁移适配📱
前端