网上找了很多在uni-app下的表格组件,实现起来都太复杂了,我只是想要一个表格单纯的可以实现首行首列可以固定,没办法看了资料后,只能自己写。下面是一个最简单的实现方式。可以自己进行后续封装来使用,自己亲自编写实测没问题,纯CSS方案。
<template>
<view class="table-container">
<view class="table">
<!-- 表头行 -->
<view class="tr">
<view class="th">时间</view>
<view class="th">AA</view>
<view class="th">BB</view>
<view class="th">CC</view>
<view class="th">DD</view>
<view class="th">EE</view>
</view>
<!-- 表格数据行 -->
<block v-for="index in 50" :key="index">
<view class="tr">
<view class="td">10:17:25</view>
<view class="td">{{index}}</view>
<view class="td">10</view>
<view class="td">20.5</view>
<view class="td">6</view>
<view class="td">16</view>
</view>
</block>
</view>
</view>
</template>
<script setup>
</script>
<style>
.table-container{
width: 100%;
height: 100%;
position: absolute;
}
/* 下面这里必须要有overflow:auto;,结合上面外部的 position: absolute; 才可以实现首行首列固定 */
.table{
width: 100%;
height: 100%;
overflow:auto;
}
.tr {
display: flex;
}
.th,.td {
/* 对每个单元格设置宽高, 宽同表格一致 */
min-width: 150rpx;
height: 60rpx;
/* 每个格背景设置透明, 滑动的时候就好隐藏 */
background-color: #fff;
display: flex;
justify-content: center;
align-items: center;
}
.th{
/* 设置背景色, 滑动的时候就不会重叠字样了. */
background-color: #f4f6ff;
text-align: center;
}
/* 表头部分 */
.tr:first-child {
/* 将第一个格设置 sticky, 往上滑则固定住 */
position: sticky;
top: 0;
/* 提升表格的重叠权重, 显示出来, 同时将内容设置为透明, 就实现了固定表头的效果 */
z-index: 1;
background-color: aqua;
}
/* 首行第一个单元格进行固定 */
/* 每行第一个单元格进行固定, 宽度和表格一致对齐 */
.th:first-child,
.td:first-child{
position: sticky;
width: 200rpx;
left: 0;
background-color: aquamarine;
}
/* 将滚动条设置隐藏 */
::-webkit-scrollbar {
width: 0;
height: 0;
}
</style>