mounted() {
// 在mounted中监听表格scroll事件 this.$refs.scrollTable.addEventListener( 'scroll',(event) => { this.adjustTable(event); }); }, ......
// target中的属性很多,可以通过控制台查看—-clientWidth可以获取除滚动条外的可视区域宽度
adjustTable(event) { this.clientWidth = event.target.clientWidth; },
获取clientWidth,可以调整表头与列对齐(最后一列的宽度不设置)
<table class="cl-body-table" cellpadding="0" cellspacing="0">
<thead :style="{'width':clientWidth+'px'}">
<th style="width:8%"></th>
<th class="cl-thead-th"></th>
</thead>
<tbody></tbody>
</table>
.......
// 表格滚动
table tbody {
display: block;
height: 495px;
overflow-y: auto;
overflow-x: hidden;
}
// 表头固定
table thead,
tbody tr {
display: table;
table-layout: fixed; /* 使用表格固定算法 必须配合上面一起使用 */
width: 100%;
}
//列宽度
.cl-thead-th { &.is-not-last { width:13.142857143% // 最后一列不设宽度,才能表头与列对齐 } }
网上最简单的表头与列对齐,由于我第一列的宽度与其他列宽度不同,导致始终不能对齐。因此我采用以下方法无效
// 表格滚动 table tbody { display: block; height: 495px; overflow-y: auto; overflow-x: hidden; } // 表头固定 table thead, tbody tr { display: table; table-layout: fixed; /* 使用表格固定算法 必须配合上面一起使用 */ width: 100%; } // 调整表头与列对齐 table thead { width:calc(100%-2em) }