问题描述: 在使用Angular 5中的完美滚动条插件时,psYReachEnd事件会多次触发。
解决方法:
下面是一个示例代码:
import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';
import { fromEvent } from 'rxjs';
import { debounceTime } from 'rxjs/operators';
@Component({
selector: 'app-scroll',
template: `
`,
styles: [`
.scroll-container {
height: 200px;
overflow-y: scroll;
}
`]
})
export class ScrollComponent implements OnInit {
@ViewChild('scrollContainer') scrollContainer: ElementRef;
ngOnInit() {
fromEvent(this.scrollContainer.nativeElement, 'scroll')
.pipe(debounceTime(500))
.subscribe(() => {
if (this.isScrolledToBottom()) {
// 处理滚动到底部的逻辑
}
});
}
isScrolledToBottom(): boolean {
const container = this.scrollContainer.nativeElement;
return container.scrollTop + container.offsetHeight >= container.scrollHeight;
}
}
在上面的代码中,我们使用了Angular的ViewChild修饰符来获取scrollContainer元素的引用。然后,我们使用rxjs的fromEvent函数来创建一个可观察对象,监听scroll事件。通过使用debounceTime操作符,我们将事件触发频率限制为500毫秒一次。最后,在事件处理程序中,我们检查滚动条是否滚动到底部,如果是,则执行相应的逻辑。
希望以上解决方法对您有所帮助。
上一篇:Angular5通过索引合并数组