angular - 如何检测 ionic 4的 ion-content 成分中的涡旋到达终点?

标签 angular scroll ionic4 ion-content

在Ionic v3 ion-content 中,存在诸如“scrollTop”之类的属性。在Ionic v4中,不再有此属性...如何确定用户是否到达内容结尾?

https://ionicframework.com/docs/v3/api/components/content/Content/
https://ionicframework.com/docs/api/content

最佳答案

这些功能仍然可用,它们位于其他位置。

在使用scrollEvents启用它之后,您需要使用ionScroll事件,然后根据getScrollElement()函数(而不是ion-content)的结果来计算高度,该函数的窗口高度是固定的。

我在下面写了一个例子。您可以删除console.log并将其收紧一些,我只是留在其中以帮助您了解发生了什么。

示例页面:

<ion-header>
  <ion-toolbar>
    <ion-title>detectScrollToBottom</ion-title>
  </ion-toolbar>
</ion-header>

<ion-content [scrollEvents]="true" (ionScroll)="logScrolling($event)">
  <p *ngFor="let dummy of ' '.repeat(75).split('')">Lorem ipsum dolor sit amet consectetur adipisicing elit. Quia placeat nam sapiente iusto eligendi</p>
</ion-content>

示例代码:
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-detect-scroll-to-bottom',
  templateUrl: './detect-scroll-to-bottom.page.html',
  styleUrls: ['./detect-scroll-to-bottom.page.scss'],
})
export class DetectScrollToBottomPage implements OnInit {

  private scrollDepthTriggered = false;

  constructor() { }

  ngOnInit() {
  }

  async logScrolling($event) {
    // only send the event once
    if(this.scrollDepthTriggered) {
      return;
    }

    console.log($event);

    if($event.target.localName != "ion-content") {
      // not sure if this is required, just playing it safe
      return;
    }

    const scrollElement = await $event.target.getScrollElement();
    console.log({scrollElement});

    // minus clientHeight because trigger is scrollTop
    // otherwise you hit the bottom of the page before 
    // the top screen can get to 80% total document height
    const scrollHeight = scrollElement.scrollHeight - scrollElement.clientHeight;
    console.log({scrollHeight});

    const currentScrollDepth = $event.detail.scrollTop;
    console.log({currentScrollDepth});

    const targetPercent = 80;

    let triggerDepth = ((scrollHeight / 100) * targetPercent);
    console.log({triggerDepth});

    if(currentScrollDepth > triggerDepth) {
      console.log(`Scrolled to ${targetPercent}%`);
      // this ensures that the event only triggers once
      this.scrollDepthTriggered = true;
      // do your analytics tracking here
    }
  }

}

日志示例:

example log output

关于angular - 如何检测 ionic 4的 ion-content 成分中的涡旋到达终点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56886454/

相关文章:

android - 构建和运行时出现 Ionic Cordova 错误

angular - 带有插值的 graphql-codegen 动态场

objective-c - 仅调整 UIWebView 的内容大小/适合内容?

javascript - 如何正确实现带id的路由?

java - 通过代码 ScrollView

jquery - 滚动到重复元素

angular - NgRx:如何在 meta-reducers 中使用服务?

css - 具有 flex 模式的 Ngx-datatable 响应行详细信息

angular - 这个效果的名称是什么?

angular - 将按钮添加到谷歌地图 Angular2