Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/466.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/css/37.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 角度9在单个元素滚动上添加类_Javascript_Css_Angular - Fatal编程技术网

Javascript 角度9在单个元素滚动上添加类

Javascript 角度9在单个元素滚动上添加类,javascript,css,angular,Javascript,Css,Angular,我需要将类添加到单个元素滚动条上的元素。我创建了一个slackblitz示例。我知道如何在全身卷轴上添加类。但是,我需要添加特定的元素滚动。 在本例中,我需要在滚动div#段落时添加类 提前谢谢 您可以尝试向模板中的段落元素添加事件: <div id="paragraph" (scroll)="onDivScroll()"> 您必须根据需要添加额外的逻辑,但您应该能够通过这种方式将单个元素文本变为绿色。您可以创建一个侦听其主机滚动事件的指令。

我需要将类添加到单个元素滚动条上的元素。我创建了一个slackblitz示例。我知道如何在全身卷轴上添加类。但是,我需要添加特定的元素滚动。 在本例中,我需要在滚动div#段落时添加类

提前谢谢


您可以尝试向模板中的段落元素添加事件:

<div id="paragraph" (scroll)="onDivScroll()">

您必须根据需要添加额外的逻辑,但您应该能够通过这种方式将单个元素文本变为绿色。

您可以创建一个侦听其主机滚动事件的指令。类似这样的东西会起作用:

@Directive({
  selector: '[appScroll]'
})
export class ScrollDirective {

  @Input() scrollClass: string;

  constructor(private el: ElementRef, private renderer: Renderer2) { }

  @HostListener("scroll", [])
  onScroll() {
    if (this.el.nativeElement.scrollTop > 20) {
      this.renderer.addClass(this.el.nativeElement, this.scrollClass)
    }
  }

}
我把你的代码示例分叉了


注意:尽量避免使用
document.getElementById
直接访问DOM。为此,请始终使用角度工具。

谢谢。任何想法,如何删除添加的类滚动回到顶部。调用
this.renderer.removeClass(this.el.nativeElement,this.scrollClass)
在任何您想要的事件上。谢谢。任何想法,如何删除添加的类滚动回到顶部。
@Directive({
  selector: '[appScroll]'
})
export class ScrollDirective {

  @Input() scrollClass: string;

  constructor(private el: ElementRef, private renderer: Renderer2) { }

  @HostListener("scroll", [])
  onScroll() {
    if (this.el.nativeElement.scrollTop > 20) {
      this.renderer.addClass(this.el.nativeElement, this.scrollClass)
    }
  }

}