Angular 4 @HostListener窗口滚动事件奇怪地在Firefox中不起作用

Jul*_*lsy 6 firefox scroll angular

@HostListener('window:scroll', [])在Angular 4应用程序中使用,以便在滚动时向标题添加其他类.它在Chrome中运行良好,但我注意到在Firefox 54.0(我认为它是最新的当前版本)中没有添加该类,它根本不执行onWindowScroll()方法.可能是什么原因?

这是代码的一部分和Plunker演示(顺便说一句,在Chrome中也可以正常工作但在Mozilla中不行):

public isScrolled = false;
constructor(@Inject(DOCUMENT) private document: any) {}
@HostListener('window:scroll', [])
onWindowScroll() {
    const number = this.document.body.scrollTop;
    if (number > 150) {
        this.isScrolled = true;
    } else if (this.isScrolled && number < 10) {
        this.isScrolled = false;
    }
}
Run Code Online (Sandbox Code Playgroud)


任何帮助将非常感激.

Avi*_*Avi 12

试试这个:

@HostListener('window:scroll', ['$event'])
onWindowScroll($event) {
    console.log("scrolling...");
}
Run Code Online (Sandbox Code Playgroud)

我更喜欢这个:

this.eventSubscription = Observable.fromEvent(window, "scroll").subscribe(e => {
                this.onWindowScroll();
            });
Run Code Online (Sandbox Code Playgroud)


小智 10

我确实遇到了同样的问题并通过使用window.scrollY而不是使用this.document.body.scrollTop来解决它,使其在Mozila Firefox中运行.我知道这很奇怪,但它确实有效.


Nis*_*ngh 10

我是如何解决这个问题的

在 Firefox、chrome 和其他浏览器上完美运行

概念: 如果您没有任何其他滚动元素,您现在可以收听作为主体的滚动元素的属性

@HostListener('window:scroll', ['$event']) onWindowScroll(e) {
    console.log(e.target['scrollingElement'].scrollTop)

    // Your Code Here

  }
Run Code Online (Sandbox Code Playgroud)


小智 6

这个 Angular 指令适用于 Chrome 和 Firefox:

import { Directive, Output, EventEmitter, HostListener, ElementRef, OnDestroy 
} from '@angular/core';
import { Observable } from 'rxjs/Rx';
import 'rxjs/add/observable/fromEvent';

@Directive({
  selector: '[scroll]'
})
export class ScrollEventDirective implements OnDestroy {
  @Output() scrollPosition: EventEmitter<number> = new EventEmitter<number>
  ();

  private scrollEvent$;

  constructor(private el: ElementRef) {
    this.scrollEvent$ = Observable.fromEvent(this.el.nativeElement, 
    'scroll').subscribe((e: any) => {
      this.scrollPosition.emit(e.target.scrollTop);
    });
  }

  ngOnDestroy() {
    this.scrollEvent$.unsubscribe();
  }
}
Run Code Online (Sandbox Code Playgroud)

在 DIV 元素上使用指令:

<div scroll (scrollPosition)="scrollChanged($event)">...</div>
Run Code Online (Sandbox Code Playgroud)