如何检查用户是否已向下滚动(或交叉)到 Angular7 中的特定元素(基于 id)?

Mah*_*esh 3 html css typescript angular7

如何检查用户是否已向下滚动(或交叉)到浏览器中的特定元素(基于 id),以便我可以检查条件并在 Angular 7 中动态分配类名?

j3f*_*3ff 6

基本上,您可以使用HostListener和Angular 监听窗口滚动事件,window:scroll如下所示:

@HostListener('window:scroll', ['$event'])
onWindowScroll() {
  // handle scrolling event here
}
Run Code Online (Sandbox Code Playgroud)

可用StackBlitz 示例进行下面的解释

ScrolledTo 指令

在这种情况下,为了获得最大的灵活性,我要做的是创建一个指令来应用于任何会公开两种状态的 HTML 元素:

  • 到达true当滚动位置到达应用指令的元素的顶部时
  • passtrue当滚动位置超过应用指令的元素高度时
import { Directive, ElementRef, HostListener } from '@angular/core';

@Directive({
  selector: '[scrolledTo]',
  exportAs: 'scrolledTo', // allows directive to be targeted by a template reference variable
})
export class ScrolledToDirective {
  reached = false;
  passed = false;

  constructor(public el: ElementRef) { }

  @HostListener('window:scroll', ['$event'])
  onWindowScroll() {
    const elementPosition = this.el.nativeElement.offsetTop;
    const elementHeight = this.el.nativeElement.clientHeight;
    const scrollPosition = window.pageYOffset;

    // set `true` when scrolling has reached current element
    this.reached = scrollPosition >= elementPosition;

    // set `true` when scrolling has passed current element height
    this.passed = scrollPosition >= (elementPosition + elementHeight);
  }
}
Run Code Online (Sandbox Code Playgroud)

分配 CSS 类

使用模板引用变量,您将能够检索#myTemplateRef="scrolledTo"在 HTML 代码中指定指令导出的那些状态,并根据返回的值根据需要应用 CSS 类。

<div scrolledTo #scrolledToElement="scrolledTo">
  <!-- whatever HTML content -->
</div>

<div
  [class.reached]="scrolledToElement.reached"
  [class.passed]="scrolledToElement.passed">
  <!-- whatever HTML content -->
</div>
Run Code Online (Sandbox Code Playgroud)

这样,您就可以在其他 HTML 元素或监视元素本身上分配类......几乎可以按照您的需要,根据您的需要!

希望能帮助到你!