首页 > 解决方案 > Angular 12: Add class base on element current position and window position

问题描述

I'm trying to add some scrolling animation to my app which is something like this: when the user start scrolling, elements will start sliding in or out depending on whether they are about to be in-view or soon to be out-of-view.

My idea is to keep track of the window position like this:

curWinPos: number = 0;
@HostListener('window:scroll', ['$event']) 
windowScrolled($event: Event) {
  this.curWinPos = window.scrollY;
}

and then add the "show" class to the element base on their current position compare to curWinPos:

<div [class.show]="$element.getBoundingClientRect().top === curWinPos"

I have no idea how to access the "$element" in the template though

标签: cssangularanimationsassscroll

解决方案


推荐阅读