我正在Angular 4应用中使用@HostListener('window:scroll', [])
,以便在滚动时向标头添加其他类。它在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;
}
}
任何帮助将不胜感激。
尝试以下:
@HostListener('window:scroll', ['$event'])
onWindowScroll($event) {
console.log("scrolling...");
}
我更喜欢这个:
import { fromEvent } from "rxjs";
...
this.eventSubscription = fromEvent(window, "scroll").subscribe(e => {
this.onWindowScroll();
});
我确实遇到了相同的问题,并通过使用 window.scrolly 解决了它,而不是使用 this.document.body.body.scrolltop 使其在Mozila Firefox中起作用。我知道这很奇怪,但可以工作。
我如何解决此
在Firefox,Chrome和其他浏览器上完美工作
概念:如果您没有任何其他滚动元素
@HostListener('window:scroll', ['$event']) onWindowScroll(e) {
console.log(e.target['scrollingElement'].scrollTop)
// Your Code Here
}
该角指令将在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();
}
}
使用DIV元素上的指令:
<div scroll (scrollPosition)="scrollChanged($event)">...</div>