最近项目用的是iview开发的,最初一开始是被iview的表格丰富的功能吸引了,但是由于iveiw还不是很稳定且一直在升级,做到后来要上线了,因为真实数据量比较大,用iveiw一个页面渲染时间长达22s之多,这样的效果是显然不能忍受的,然后直接用vue,不到2s页面。然后决定放弃iview了,但是还是想要iview中的表格左侧,头部滚动固定的功能,然后就打算自己手写。
一开始在网上搜了一下固定头尾。这种也满足不了需求,于是打算手写,发现也没有想象中的那么复杂。废话不多说,直接贴代码。
scrollTable.scroll-table{overflow-x: scroll;}
table {border-collapse:collapse;}
th,td{border: none;white-space: nowrap;}
th{background-color: aqua;}
td:first-child{background-color: cadetblue;}
.scroll-table {border: 1px solid #ddd;max-height: 400px;}
.scroll-table th,.scroll-table td{position: relative;}
.scroll-table th{position: relative;z-index:100;top:-1px;left:0;}
.scroll-table th.fixed-th-both{z-index:200;}
.fixed-td-left{position: relative;z-index:10;bottom: 0;left:0;}
.scroll-table .td-border{position: absolute;top:0;left:0;width:100%;height:100%;border:1px solid #ddd;}
表头1表头2表头3表头4表头5表头6表头7表头8表头9表头10表头11表头12表头13表头14表头15表头16
第一栏999999999111188888222222222222222222221111111199999999911119999888882222222222222222222211118777第二栏111199999999911118888822222222222222222222111111119999999991111888882222222222222222222211118777...
...
$('.scroll-table tbody tr').find('td:first-child').addClass('fixed-td-left');
$('.scroll-table th').addClass('fixed-td-top');
$('.scroll-table').scroll(function(){
var _this = $(this);
_this.find('.fixed-td-top').css('top',this.scrollTop-1);
_this.find('.fixed-td-left').css('left',this.scrollLeft);
_this.find('.fixed-th-both').css('left',this.scrollLeft);
});
效果图
把td,th都设定为相对定位,滚定时改变定位,为什么要设置相对定位不设置绝对定位呢,应为如果th设置了绝对定位,那么表格单元格宽度就不能根据表头自适应了,表头和表格宽度分配不一致。
当单元格定位起来时,border并不会跟随内容滚动,所以把我这放了个div来做border
需要注意的是左上角的单元格不论是左右滚动还是上下滚动都需要固定在左上方