【问题标题】:Check if user has scrolled to the bottom in Angular 2检查用户是否在 Angular 2 中滚动到底部
【发布时间】:2016-11-10 02:39:13
【问题描述】:

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

【问题讨论】:

标签: angular angular2-template angular2-directives


【解决方案1】:

//你可以用这个。

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

【讨论】:

  • 必须将其写为 @HostListener("window:scroll", []) 才能使其工作。
  • "document.body.offsetHeight - 1" 可能会更好。
  • 对我来说这有效 - (window.innerHeight + window.scrollY) >= document.body.scrollHeight
  • 这可行,但就像底部上方的一些像素一样。我们如何检测用户是否已经滚动到最后?
【解决方案2】:

对我来说,聊天框的底部不在页面底部,因此我无法使用 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>

【讨论】:

    【解决方案3】:

    而不是使用 document.body.offsetHeight 使用这个:

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

    【讨论】:

    • scrollHeight 值与 offsetHeight 有何不同?
    【解决方案4】:

    使用 @HostListener 装饰器监听 window:scroll 事件。

    @HostListener('window:scroll', [])
    onScroll(): void {
      const triggerAt: number = 128; 
      /* perform an event when the user has scrolled over the point of 128px from the bottom */
      if (document.body.scrollHeight - (window.innerHeight + window.scrollY) <= triggerAt) {
        doSomething();
      }
    }
    

    使用scrollHeight 而不是offsetHeight 或clientHeight 如果内容将事件挂钩到可滚动。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-16
      • 1970-01-01
      • 1970-01-01
      • 2018-12-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多