javascript - 如何在滚动到 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
推荐阅读
- python - 当我尝试将字符串插入列表时,为什么会出现此错误?
- python - 在python中用序数、大小和直方图维度绘制散点图
- algorithm - 这个函数的时间复杂度是多少?
- node.js - 为什么我的 graphql apollo 解析器没有被调用?
- python - Python - 基于多列组合两个数据框
- prolog - Prolog 中的列表拆分
- javascript - 如何使 Lang 选择器根据本地存储中的值工作?
- python - 运行时错误:迭代期间字典大小改变
- c++ - 试图用 lambda 找到 2D 向量的最小元素
- android - 一旦流开始,Android音频效果不会实时附加到音频流