<view class="table-box">
<view class="table">
<!-- 表格标题 -->
<view class="tr">
<view class="th" wx:for="{
{thList}}" wx:key="index">{
{item}}</view>
</view>
<!-- 表格内容 -->
<view class="tr" wx:for="{
{trList}}" wx:for-item="tdList" wx:key="index">
<view class="td" wx:for="{
{tdList}}" wx:key="index_">{
{item}}</view>
</view>
</view>
</view>
Page({
data: {
thList: ['name', 'age', 'sex', 'long'],
trList: [ // 用二维数组把每一行的数据汇总
['张三', 18, '男', '188cm'],
['李四', 19, '男', '178cm'],
['王五', 20, '男', '168cm'],
['赵六', 21, '男', '158cm']
]
}
})
.table-box {
height: 100%;
overflow-x: auto;
margin: 30rpx;
background: #fff;
border-radius: 16rpx;
}
.table {
border-radius: 8rpx;
margin: 0 auto;
display: table;
table-layout: fixed;
border-collapse: collapse;
overflow-x: auto;
word-break: keep-all;
background-color: #FFFFFF;
border-radius: 16rpx;
}
.tr {
display: table-row;
}
.th {
display: table-cell;
height: 80rpx;
line-height: 80rpx;
text-align: center;
border: 2rpx solid #F3F4F7;
border-right: none;
border-bottom: none;
padding: 0 30rpx;
color: #747477;
white-space: nowrap;
}
.td {
padding: 0 10rpx;
display: table-cell;
height: 60rpx;
vertical-align: middle;
text-align: center;
border: 2rpx solid #F3F4F7;
border-right: none;
}
.th:first-child,
.td:first-child {
position: sticky;
left: -2rpx;
background: #fff;
}
.th:first-child {
background: #fff;
z-index: 1; /*左上角单元格z-index,切记要设置,不然表格纵向横向滚动时会被该单元格右方或者下方的单元格遮挡*/
}
注:
display: table-cell垂直居中使用:vertical-align: middle;
第一行/列固定: table-layout: fixed; 和 position:sticky;
postion的sticky粘性定位
粘性定位可以被认为是相对定位和固定定位的混合。元素在跨越特定阈值>前为相对定位,之后为固定定位。
sticky元素会“固定”在离它最近的一个拥有“滚动机制”的祖先上(当该祖先的overflow是hidden、scroll、auto、overlay时),即便这个祖先不是最近的真实可滚动祖先。
table-layout的fixed
table-layout css属性定义了用于布局表格单元格,行和列的算法。值可以是:auto、fixed。
- auto
表格和单元格的宽度取决于其包含的内容。- fixed
表格宽度通过表格的宽度来设置,某一列的宽度仅由该列首行的单元格决定,其他行单元格的宽度不会影响整列的宽度。
分析:在表格中,某些列需要指定不同的宽度,所以表格的table-layout css属性需要设置为fixed。