本来以为这种表格固定就是靠css就可以了,但发现主流的一些组件库显然不是这么搞的,还是拿js操控的。
cloneNode是原生js,默认克隆父节点,如果传了true会连子节点一起拷贝。
以固定头部为例,表格固定原理是,拷贝出一个空的table父节点,再把要固定的节点取出来,appendChild进这个table节点,再用绝对定位放到头部即可。
mounted() {
if (this.height) { // 固定表头必须有height属性
this.table = this.$refs.table;
this.taleWrapper = this.$refs.tableWrapper;
let copyTable = this.table.cloneNode(); // 拷贝表格
let thead = this.table.children[0];
this.taleWrapper.style.paddingTop = thead.getBoundingClientRect().height + 'px';
copyTable.appendChild(thead); // 将原表格的thead 移动到拷贝的表格中
this.taleWrapper.appendChild(copyTable); // 将拷贝后的结果插入到页面上
copyTable.classList.add('fiex-header')
}
},
.fiex-header{
position:absolute;
top:0;
left:0;
width: 100%;
}
.table-wrapper {
width: 80%;
margin: 0 auto;
position: relative
}