Handsontable合并表头,实现rowspan效果

背景#

使用handsontable只能进行跨列的合并,如果跨行的话就有api提供,我们需要对表头进行跨行合并

实现#

这里学习这边博文提供的一个思路,就是假设需要对表格第一行的跨行合并的话,

  • 分析第一行的哪些元素是要进行跨行合并的? 这里我猜作者考虑的是如果跨列的话就不考虑这个元素、然后排除hansontable中隐藏列的类(hiddenHeader)

博文链接:https://juejin.cn/post/7097164460762071048

代码如下:
html

<style>
  #grid {
    width: 800px;
    height: 500px;
    background-color: #efefef;
  }
</style>
<div id="grid"></div>

index.js

let data = [
  ['张三', 90, 70, 88, 100, 92, 95, 87, 98, 99, 100, 55, 60 ],
  ['李四', 89, 92, 88, 100, 92, 95, 97, 98, 55, 92, 55, 60 ],
  ['王五', 100, 70, 82, 99, 92, 95, 97, 98, 69, 88, 55,  99],
  ['赵六', 77, 91, 81, 75, 91, 75, 96, 91, 77, 96, 55, 60 ]
]

new Handsontable(document.getElementById('grid'), {
  data: data,
  manualColumnResize: true,
  colHeaders: true,
  licenseKey: 'non-commercial-and-evaluation',
  rowHeaders: true,
  manualColumnResize: true,
  width: '800',
  height: '500',
  readOnly: true,
  outsideClickDeselects: false,
  rowHeights: 28,
  columnHeaderHeight: 32,
  className: 'htMiddle htCenter',
  nestedHeaders: [
    ['姓名',
       {
        label: "2021年",
        colspan: 6
      }, {
        label: "2022年",
        colspan: 6
      }],
    ['', '语文', '数学', '外语', '政治', '历史', '地理', '语文', '数学', '外语', '政治', '历史', '地理']
  ],
  afterGetColHeader: function(col, th) {
    setTimeout(() => {
      if (col === -1) {
        const theads = th.parentNode.parentNode // 获取当前表头的thead对象
        const trs = theads.getElementsByTagName('tr') // 获取所有行
        const trCols1 = trs[0].getElementsByTagName('th') // 获取第一行所有列
        const trCols2 = trs[1].getElementsByTagName('th') // 获取第二行所有列
        if (trCols1.length === trCols2.length) {
          // 行号表头将第一行的底部边框去除掉,符合合并单元格样式
          // 此处不能执行rowSpan属性,否则出现第二行合表头数据错位
          trCols1[0].style.borderBottom = 'none'
          for (let i = 1; i < trCols1.length; i++) {
            // 如果单元格不包含colSpan属性且不是隐藏的单元格,则表明需要合并行,否则,则表明不需要合并行
            if (!trCols1[i].getAttribute('colSpan') && trCols1[i].className !== 'hiddenHeader') {
              trCols1[i].rowSpan = 2
              trCols1[i].style.verticalAlign = 'middle'
              trCols1[i].style.height = '64px'
              // 将第二行表格隐藏,并将第一行的底部边框去除
              trCols2[i].className = 'hiddenHeader'
              trCols1[i].style.borderBottom = 'none'
            }
          }
        }
      }
    }, 100)
  }
});

效果#

posted @   ^Mao^  阅读(1271)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示
主题色彩