效果
数据自动循环滚动展示,鼠标经过时暂停滚动
Html
<div #listDiv class="list-rolling">
<div
class="list-scroll"
[style.top]="topStyle"
(mouseenter)="mouseenterEvent()"
(mouseleave)="mouseleaveEvent()"
>
<div *ngFor="let item of records" class="item" nz-row [nzGutter]="32">
{{ item.name }}
</div>
</div>
</div>
Scss
.list-rolling {
position: relative;
overflow: hidden;
padding: 0 16px;
height: 100%;
.list-scroll {
position: absolute;
left: 0;
width: 100%;
.item {
height: 40px;
white-space: nowrap;
text-overflow: ellipsis;
overflow: hidden;
}
}
}
ts
import {
Component,
OnInit,
AfterViewInit,
ViewChild,
ElementRef,
} from '@angular/core';
@Component({
selector: 'app-list-rolling',
templateUrl: './list-rolling.component.html',
styleUrls: ['./list-rolling.component.scss'],
})
export class ListRollingComponent implements OnInit, AfterViewInit {
@ViewChild('listDiv') listDiv: ElementRef;
records = [];
recordsLength = 0;
listBoxHeight = 0;
top = 0;
topStyle = '';
timer;
constructor() {}
ngOnInit(): void {
clearInterval(this.timer);
this.getDataList();
this.setTop(this.top);
}
ngAfterViewInit(): void {
this.listBoxHeight = this.listDiv.nativeElement.clientHeight;
}
// 设置
setTop(top) {
this.topStyle = `${top}px`;
}
getDataList() {
this.apiService.listData().subscribe(response => {
const { success, data } = response;
if (success) {
this.records = data;
this.recordsLength = this.records.length;
// 盒子高度大于数据高度时滚动
if (this.listBoxHeight < this.recordsLength * 40) {
const records = this.records;
this.records = this.records.concat(records);
this.scrollList();
}
}
});
}
scrollList() {
const { listBoxHeight, recordsLength } = this;
const scrollH = recordsLength * 40;
if (listBoxHeight < scrollH) {
this.timer = setInterval(() => {
if (-this.top >= scrollH / 2) {
this.top = -40;
} else {
this.top = this.top - 40;
}
this.setTop(this.top);
}, 2000);
}
}
mouseenterEvent() {
clearInterval(this.timer);
}
mouseleaveEvent() {
this.scrollList();
}
}