角度版本:6.0.0
Cli:6.0.0
如果页面滚动了500px或更多,我已经使用了HostListener以下命令来显示滚动到顶部按钮,反之亦然。
isSectionFixed : boolean = false;
@HostListener('window:scroll', ['$event.target'])
onWindowScroll(event) {
let number = window.pageYOffset || 0;
if (number > 500) {
this.isSectionFixed = true;
} else if (this.isSectionFixed && number < 500) {
this.isSectionFixed = false;
}
}
它工作正常,但页面变得无用。
此代码用于app.component.ts
只有极少数的页面像产品搜索页面之类的亚马逊一样无响应,但滚动次数无限。
我也尝试过使用Observable
eventSubscription = Observable.fromEvent(window, "scroll").subscribe(e => {
this.scrollY = window.scrollY;
});
在我在onWindowScroll
函数内或在subscribe callback
的第二种情况下添加一些代码之前,它一直很好。
相同的解决方案在服务器端重做的角度应用中效果很好。
任何帮助将不胜感激,我现在无法共享指向私有应用程序的链接。
答案 0 :(得分:1)
尝试在滚动“可观察”上使用运算符throttletime和distinctUntilChanged,以使滚动事件不会频繁地映射到一个值,并且只有在实际更改时才发出新的布尔值。
import { OnDestroy } from '@angular/core';
import { fromEvent, Subject } from 'rxjs';
import { distinctUntilChanged, map, takeUntil, throttleTime } from 'rxjs/operators';
const scrolledDown$ = fromEvent(window, 'scroll').pipe(
throttleTime(10), // only emit scroll events every 10 ms, set this to your needs
map(() => window.pageYOffset > 500), // map to a boolean value
distinctUntilChanged(), // only emit if the value has changed
takeUntil(this.destroy$) // unsubscribe when the component gets destroyed
);
private destroy$: Subject<void> = new Subject<void>();
ngOnDestroy() {
this.destroy$.next();
this.destroy$.complete();
}
scrolledDown$
将发出一个布尔值,该布尔值指示用户是否滚动到某个点以下(window.pageYOffset
是否大于500)。本质上,这是您的isSectionFixed
值作为可观察值。
可以使用模板中的scrolledDown$
管道订阅asnyc
,也可以根据需要手动在代码中进行订阅。如果您手动订阅,请不要忘记在组件被销毁时退订(这就是我的代码中的destroy$
的意思。)
修改
您还可以尝试通过将事件监听器设为passive来提高scoll性能。您可以使用default-passive-events轻松实现这一目标。