首页 > 解决方案 > 如何在滚动到 Angular 8 中的特定元素时动态更改类?

问题描述

我可以使用 onMouseWheel 轻松完成此操作,但它不适用于使用键盘(箭头键)滚动的用户。这是我想要使用 onMouseWheel 的功能的演示。

    <h2  [ngClass]="{ 'scrolled-into-view' : scrolled }"  (wheel)="onMouseWheel($event)">
      This text should turn red when scrolled into view.
    </h2>
  scrolled = false;
  onMouseWheel(evt) {
    this.scrolled = true;
  }  

https://angular-ivy-5hgjb5.stackblitz.io

标签: javascriptangularscrollevent-handling

解决方案


我能够通过使用 HostListener 装饰器来处理滚动事件来解决这个问题。从那里我将 window.scroll 与要滚动到视图中的元素的 offsetTop 进行了比较。

这是组件JS:

import { Component, HostListener, ElementRef, ViewChild } from "@angular/core";

@Component({
  selector: "my-app",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent {
  flag = false;
  @ViewChild("scrolledToElement", { static: false })
  scrolledToElement: ElementRef;
  @HostListener("window:scroll", ["$event"])
  onScroll(event) {
    if (window.scrollY > this.scrolledToElement.nativeElement.offsetTop) {
      this.flag = true;
      console.log("flag", this.flag);
    }
  }
}

HTML

<div class="blue">
    When you scroll to the div below, it should turn from red to green.
</div>
<div #scrolledToElement class="second-block" [ngClass]="flag ? 'red' : 'green' "></div>

演示: https ://stackblitz.com/edit/angular-ivy-xhb4yw?file=src/app/app.component.html


推荐阅读