问题描述:
最近在开发一个大屏数据显示,需要一个表格,能够上下滚动显示数据。发现用第三方的UI库实现起来不太好看。所以自己动手写。
效果就是红色框圈起来的部分,表头信息不动,然后表格内容上下滚动
方法实现:
HTML部分
// 我这边的数据是后端返回的,具体情况可以自己看着配置
<div class="table-container">
<table class="table">
// 这个是表头部分的设置,
<thead>
<th
v-for="head in data[0].TodaysPromotionInfoList[index]
.TodaysPromotionInfoTableHead"
:key="head.Field"
>
{{ head.Descriptions }}
</th>
</thead>
// 这个地方是表格数据部分
// 在这里我根据数组的长度做了判断,当数组长超过2的时候,添加这个滚动的动画
// 而且为了显示效果好看,我用js部分做了控制,页面刚显示时,动画会在2秒之后执行,动画时间设置了15秒,每次循环,暂停2秒
<tbody
:class="{
scroll:
data[0].TodaysPromotionInfoList[index]
.TodaysPromotionInfo.length > 2 && isAnimating,
}"
>
// 设置行数
<tr
v-for="i in data[0].TodaysPromotionInfoList[index]
.TodaysPromotionInfo.length"
:key="i"
class="trAnimation"
>
// 设置每行每个单元格
<td
v-for="(value, key) in data[0].TodaysPromotionInfoList[
index
].TodaysPromotionInfo[i - 1]"
:key="key"
>
{{ value }}
</td>
</tr>
</tbody>
</table>
</div>
js部分:
export default {
// 父组件传来的数据
props: ["midTopBottomDataWatch"],
watch: {
midTopBottomDataWatch(newVal) {
if (newVal) {
this.data = this.midTopBottomDataWatch;
// 设置动画每次循环暂停2秒之后再执行
this.startAnimation();
}
},
},
data() {
return {
data: [],
isAnimating: false,
};
},
methods: {
startAnimation() {
this.isAnimating = true;
this.animate();
},
animate() {
setTimeout(() => {
this.isAnimating = false;
setTimeout(() => {
this.isAnimating = true;
this.animate();
}, 2000); // 设置停止时间为2秒
}, 17000); // 动画持续时间为2秒
},
},
};
css部分:
.table-container {
width: 95%;
margin: 0 auto;
height: calc(100% - 50px);
overflow: hidden;
position: relative;
}
.table {
width: 95%;
margin: 0 auto;
border-collapse: separate;
border-spacing: 0;
}
.table thead th {
position: sticky;
top: 0;
background-color: #3a8ee6;
z-index: 2000;
}
.table td {
border: 1px solid #ccc;
padding: 8px;
}
.scroll {
animation: scrollTable 15s linear infinite;
animation-delay: 2s;
}
@keyframes scrollTable {
0% {
transform: translateY(0);
}
100% {
transform: translateY(-100%);
}
}