Angular2数据滚动展示

效果

数据自动循环滚动展示,鼠标经过时暂停滚动

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();
  }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值