首页 > 解决方案 > 当元素进入视野时触发 CountUp 功能

问题描述

我正在使用这个库

https://github.com/inorganik/ngx-countUp

有没有办法只在到达数字部分时激活计数动画

换句话说,<h1 [countUp]="345">0</h1>当元素滚动到视图中时触发它()

那可能吗?

标签: angulartypescript

解决方案


演示 Viewchild是一种方法。

在 html 中将值设为参数。

<h1 #counter [countUp]="param">0</h1>

在组件中

@ViewChild('counter') counter: ElementRef;
param=0;

使用 hostlistener 监听滚动并检查滚动是否到达 html,如果是,将计数更改为 365

@HostListener('window:scroll', ['$event']) // for window scroll events
onWindowScroll(event) {
   var rect = this.counter.nativeElement.getBoundingClientRect();
   var elemTop = rect.top; var elemBottom = rect.bottom;
   (elemTop >= 0) && (elemBottom <= window.innerHeight) ? this.param=365:null
}

推荐阅读