如何在滚动到 Angular 8 中的特定元素时动态更改 class?
How do you change a class dynamically on scrolling to a specific element in 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;
}
我能够通过使用 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
我可以使用 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;
}
我能够通过使用 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