getBoundingClientRect
用bottom举例, 获取到的数据是元素底部相对于屏幕上边的距离
const client = $dom.getBoundingClientRect();
1、如果元素位于屏幕上面的不可见区域,client.bottom 会是负数
2、如果元素位于屏幕下面不可见区域,client.bottom > window.innerHeight
假如有个滚动加载的需求:
1、元素需要滚动加载,那么首先已经加载的部分的client.bottom 肯定是 大于 window.innerHeight
2、当逐渐向下滚动,client.bottom 会越来越小,当client.bottom < window.innerHeight 时, 它就出现在可视区域了。
demo代码
let subscription = fromEvent(window, "scroll")
.pipe(debounceTime(50), takeUntil(this.destroy$))
.subscribe(() => {
if (this.isLoading) {
return;
}
if (this.list.length < this.total) {
const client = $dom.getBoundingClientRect();
// 最后一条记录出现在屏幕高度90%的位置就开始加载
if ( client.bottom < window.innerHeight * 0.9 && client.bottom > 0 ) {
this.isLoading = true;
setTimeout(() => {
this.isLoading = false;
this.getData();
this.cdr.detectChanges();
}, 1500);
}
} else {
subscription.unsubscribe();
}
this.cdr.detectChanges();
});