Loading

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 @ 2022-10-26 23:14  ^Mao^  阅读(920)  评论(0编辑  收藏  举报