html
<div class="自定义样式">
<table>
<thead>
<tr class="table-title">
<th>x1</th>
<th>x2</th>
<th>x3</th>
<th>x4</th>
<th>x5</th>
</tr>
</thead>
</table>
<div class="scroll-box">
<table #table class="tab-scroll">
<tbody>
<tr *ngFor="let item of dataSet">
<td>{{item.x1}}</td>
<td>{{item.x2}}</td>
<td>{{item.x3}}</td>
<td>{{item.x4}}</td>
<td>{{item.x5}}</td>
</tr>
</tbody>
</table>
</div>
</div>
ts
//引入组件
@ViewChild('table') table: ElementRef;
// 表格属性初始化
sTab;
tbody;
speed: number;
tbdh: number;
intervalID;
timeoutID;
// 表格数据
dataSet: Array<any> = [
{ "x1":"1",
"x2":"1",
"x3":"1",
"x4":"1",
"x5":"1"
},
{ "x1":"1",
"x2":"1",
"x3":"1",
"x4":"1",
"x5":"1"
},
{ "x1":"1",
"x2":"1",
"x3":"1",
"x4":"1",
"x5":"1"
},
{ "x1":"1",
"x2":"1",
"x3":"1",
"x4":"1",
"x5":"1"
},
{ "x1":"1",
"x2":"1",
"x3":"1",
"x4":"1",
"x5":"1"
},
{ "x1":"1",
"x2":"1",
"x3":"1",
"x4":"1",
"x5":"1"
},
{ "x1":"1",
"x2":"1",
"x3":"1",
"x4":"1",
"x5":"1"
}
];
setScroll() {
this.sTab = this.table.nativeElement; // 要滚动的表
this.tbody = this.sTab.getElementsByTagName('tbody')[0]; // 要滚动表格的内容
if (this.dataSet.length > 6) {
//设置5s后开始滚动(只执行一次)-- setTimeout() 此定时器只执行一次
this.timeoutID = setTimeout(() => {
// 每次滚动的距离
this.speed = this.sTab.getElementsByTagName('td')[0] && this.sTab.getElementsByTagName('td')[0].offsetHeight;
this.tbdh = this.tbody.offsetHeight; // 整个表的高度,是因为上边的边不算滚动
//设置滚动时间:1.2s滚动一次(持续执行)-- setInterval() 此定时器 无限循环执行回调函数; 除非调用clearInterval()方法
this.intervalID = setInterval(() => this.scrollTop(), 1200);
}, 5000);
}
}
/*轮动位置处理*/
scrollTop() {
const t = this.sTab.offsetTop; // 获取要滚动表的位置
if ((this.tbdh / 2 + t) < (this.speed / 2)) {// 比较 滚动的距离等于整个表的高度 即第一个表完全看不见
this.sTab.style.transition = '0s'; // 过渡动画设为0秒
this.sTab.style.top = 0; // 位置设为初始位置
this.scrollTop(); // 因为偷梁换柱消耗了一次过程,所以把这一次过程补回来
} else {
this.sTab.style.transition = '1s';
this.sTab.style.top = t - this.speed + 'px';
}
}
效果如下(是动态滚动的):