vue固定表头和列
这篇文章基于原生html+vue实现表头固定和列固定,如果是使用了如element-ui等一般已经有相应实现组件。
1.基本思想
通过使用css中的transform(可以平移或旋转等),结合对scroll滚动条的监听实现固定表头和列。首先监听scroll滚动,获取其向上或向下滚动的距离,然后通过transform将表头上下平移,或者将制定列左右平移相应距离即可。
步骤
1.创建一个表格,指定表格高度和宽度,外层嵌套一个div盒子
2.给表格写cssh(这里通过制定class来写css,class名称会在指令中用到)
3.使用directives创建一个自定义指令(具体功能见代码)
注:这里有个问题没有解决,即同时固定列和表头,上下拖动滚动条时固定列会遮盖相应列的表头,目测是由于设置背景色导致的,后面再弄。
代码
<template>
<div class="app">
<div class="wrapper" v-fixed-thead>
<table>
<thead>
<tr>
<th v-for="index in 14" style="width: 100px;" :class="index == 1 ? 'th_blue' : 'th_red'">标题{{index}}</th>
</tr>
</thead>
<thead>
<tr>
<th v-for="index in 14" style="width: 100px;" :class="index == 1 ? 'th_blue' : 'th_red'">标题{{index}}</th>
</tr>
</thead>
<tbody>
<tr v-for="index1 in 20">
<td v-for="index in 14" style="width: 100px;" :class="index == 1 ? 'td_blue' : 'td_yellow'">{{index1}}行{{index}}列哈哈哈哈哈哈哈哈</td>
</tr>
</tbody>
</table>
</div>
</div>
</template>
<script>
export default {
directives: {
'fixed-thead': {
bind: function(el) {
el.onscroll=function(){
// 获取上下,左右滚动距离
let scrollTop=el.scrollTop;
let scrollLeft = el.scrollLeft;
// 获取组件
let theadList = el.querySelectorAll('thead');
let thLeftList = document.getElementsByClassName('th_blue');
let tdLeftList = document.getElementsByClassName('td_blue');
// 固定表头
if(theadList) {
for(let i=0; i<theadList.length; i++) {
theadList[i].style.transform='translateY('+scrollTop+'px)';
}
}
// 固定表格中含有类名为td_blue的元素
if(tdLeftList) {
for(let i=0; i<tdLeftList.length; i++) {
tdLeftList[i].style.transform = 'translateX('+scrollLeft+'px)';
}
}
// 固定表头中含有类名为th_blue的元素
if(thLeftList) {
for(let i=0; i<thLeftList.length; i++) {
thLeftList[i].style.transform = 'translateX('+scrollLeft+'px)';
}
}
};
}
}
},
}
</script>
<style lang="scss" scoped>
.app {
.wrapper {
height: 400px;
overflow: auto;
table {
border-collapse: collapse;
border: 1px solid grey;
tr {
height: 10px;
/*background-color: #ffffff;*/
.th_blue {
background-color: blue;
z-index: 2;
}
.th_red {
background-color: red;
z-index: 2;
}
.td_blue {
background-color: #ffffff;
border: 1px solid grey;
white-space: nowrap;
}
.td_yellow {
background-color: yellow;
border: 1px solid grey;
white-space: nowrap;
}
}
};
}
}
</style>
不出意外将上面的代码直接复制到你的项目中就可以查看到效果,如图:
这里是把固定头和固定列写在了一起,如果单独需要可以屏蔽掉directives中的代码。这里也设置了两个thead,目的是如果需要使用复杂表头可以这样弄,当然也可以给复杂表头指定class或者id,在directives中通过class名称或id名称去获取来设置。