Ser*_*nar 1 rxjs typescript angular
我需要在我的应用程序中实现变形浮动按钮功能。
我已经创建了所需的 CSS 类,现在我需要监听元素滚动以便能够应用一些样式。
我已经成功地实现了这一点,如下所示,并且效果很好:
fromEvent(scrollableElement, 'scroll')
.pipe(untilDestroyed(this), debounceTime(100))
.subscribe(() => {
const currentScrollPos = scrollableElement.scrollTop;
buttonTextElement.classList.toggle('d-none', prevScrollPos < currentScrollPos);
prevScrollPos = currentScrollPos;
});
Run Code Online (Sandbox Code Playgroud)
现在我正在尝试从性能角度改进这一点,我正在考虑以下场景:
是否有可能使用 RxJs 运算符来做到这一点?
小智 5
您可以尝试使用distinctUntilChanged,如下所示。仅当方向改变时,可观察对象才会发出向上或向下的信号。
lastScrollTop: number = 0;
ngOnInit() {
fromEvent(window, 'scroll')
.pipe(
untilDestroyed(this),
debounceTime(100),
map(() => {
let st = window.pageYOffset || document.documentElement.scrollTop;
let diff = st - this.lastScrollTop;
this.lastScrollTop = st <= 0 ? 0 : st;
return diff >= 0 ? 'Down' : 'Up';
}),
distinctUntilChanged()
)
.subscribe((scrollDirection) => {
console.log('Scroll Direction:',scrollDirection);
});
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1585 次 |
| 最近记录: |