How to detect scroll reached end in ion-content component of Ionic 4?

自作多情 提交于 2019-12-11 07:48:51

问题


In Ionic v3 ion-content there was properties like "scrollTop". In Ionic v4 there are no more of this properties... How could I determine if a user reached the end of the content?

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


回答1:


These features are still available they are just in a different location.

After enabling it with scrollEvents, you need to use the ionScroll event and then calculate the height based on the results of the getScrollElement() function, not the ion-content - that has a fixed height of the window height.

I've written an example below. You can remove the console.log's and tighten it up a bit, I just left them in to help you understand what's going on.

Example page:

<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>

Example code:

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 logs:



来源:https://stackoverflow.com/questions/56886454/how-to-detect-scroll-reached-end-in-ion-content-component-of-ionic-4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!