检查用户是否已在Angular 2中滚动到底部

问题描述 投票:11回答:3

检查用户是否在没有jQuery的情况下滚动到Angular2页面底部的最佳做法是什么?我是否可以访问我的应用程序组件中的窗口?如果不是我应该检查滚动到页脚组件的底部,我该怎么做?关于页脚组件的指令?有没有人完成这个?

angular angular2-template angular2-directives
3个回答
20
投票

//你可以用它

@HostListener("window:scroll", [])
onScroll(): void {
if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight) {
        // you're at the bottom of the page
    }
}

8
投票

对我来说,聊天框的底部不在页面底部,所以我无法使用window.innerHeight来查看用户是否滚动到聊天框的底部。 (我的目标是始终滚动到聊天的底部,除非用户试图向上滚动)

我使用以下代替完美的工作:

let atBottom = element.scrollHeight - element.scrollTop === element.clientHeight

一些背景:

@ViewChild('scrollMe') private myScrollContainer: ElementRef;
disableScrollDown = false

 ngAfterViewChecked() {
    this.scrollToBottom();
}

private onScroll() {
    let element = this.myScrollContainer.nativeElement
    let atBottom = element.scrollHeight - element.scrollTop === element.clientHeight
    if (this.disableScrollDown && atBottom) {
        this.disableScrollDown = false
    } else {
        this.disableScrollDown = true
    }
}


private scrollToBottom(): void {
    if (this.disableScrollDown) {
        return
    }
    try {
        this.myScrollContainer.nativeElement.scrollTop = this.myScrollContainer.nativeElement.scrollHeight;
    } catch(err) { }
}

<div class="messages-box" #scrollMe (scroll)="onScroll()">
    <app-message [message]="message" *ngFor="let message of messages.slice().reverse()"></app-message>
 </div>

0
投票

而不是使用document.body.offsetHeight使用此:

if ((window.innerHeight + window.scrollY) >= document.body.scrollHeight) { // you're at the bottom of the page }

© www.soinside.com 2019 - 2024. All rights reserved.