Как обнаружить завершение прокрутки в ионно-содержательной компоненте Ionic 4?

В Ionic v3 ion-content присутствуют свойства типа "scrollTop". В Ionic v4 больше нет этих свойств... Как я могу определить, достиг ли пользователь конца контента?

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

1 ответ

Решение

Эти функции по-прежнему доступны, они просто находятся в другом месте.

После включения с 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
    }
  }

}

Примеры журналов:

Помните, что использование событий прокрутки может вызвать проблемы с производительностью.

Вы не говорите, какую среду программирования вы используете, но с помощью vue вы можете установить ссылку на ion-content, а затем получить доступ к первому дочернему элементу shadowroot, например, чтобы получить / установить clientHeight и все другие вещи javascript. Хотя с изменением версии, конечно, это "скрытое" может измениться.

this.$refs.msg_list.shadowRoot.children[0].clientHeight
Другие вопросы по тегам