如何检测 ion-content 是否有滚动条?

5
我希望能够在ion-content中存在或不存在滚动条的情况下隐藏或显示元素。具体来说,我想在没有滚动条的情况下显示一个按钮(用于加载列表中的更多项),并在出现滚动条时隐藏它(这样通过ion-infinite-scroll加载更多项)。
我的Ionic应用程序也将部署到桌面,因此拥有大屏幕的用户一开始看不到滚动条,因此ion-infinite-scroll不会被触发。
以下是展示该问题的演示:
home.page.html
<ion-header>
  <ion-toolbar>
    <ion-title>
      Ionic header
    </ion-title>
  </ion-toolbar>
</ion-header>

<ion-content>
  <div class="ion-padding">
    <p *ngFor="let item of itemList">{{ item }}</p>

    <!-- How to hide this button when ion-content has a scrollbar? -->
    <!-- *ngIf="???" -->
    <ion-button (click)="incrementItemList(5)">Load more items</ion-button>
  </div>

  <ion-infinite-scroll (ionInfinite)="loadMoreItems($event)">
    <ion-infinite-scroll-content loadingSpinner="crescent"></ion-infinite-scroll-content>
  </ion-infinite-scroll>
</ion-content>

<ion-footer>
  <ion-toolbar>
    <ion-title>
      Ionic footer
    </ion-title>
  </ion-toolbar>
</ion-footer>

home.page.ts

import { Component } from '@angular/core';

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})
export class HomePage {

  itemList: string[] = [];

  constructor() {}

  ionViewWillEnter() {
    this.incrementItemList(5);
  }

  incrementItemList(times: number) {
    for (let i = 1; i <= times; i++) {
      this.itemList.push(`Lorem ipsum dolor sit amet consectetur adipisicing elit. Quia placeat nam sapiente iusto eligendi`);
    }
  }

  loadMoreItems(event: any) {
    setTimeout(() => {
      this.incrementItemList(15);
      event.target.complete();
    }, 1000);
  }

}

我使用的是Ionic 4.5.0和Angular。

我尝试使用 getScrollElementscrollHeightclientHeightoffsetHeight,但都没有成功。

有什么建议吗?


你能设置一个初始值为false的标志,当你调用loadMore方法时将其设为true吗?是的,如果它起作用,那么在加载额外数据后,你还需要再次将标志反转为false。 - Sunny Parekh
@SunnyParekh 这并不是一个万无一失的解决方案,因为屏幕大小因用户而异,并且滚动条可能在第一次调用loadMore方法后不会出现,因为可能没有足够的内容来触发滚动条。无论如何,还是谢谢你的帮助。 - nunoarruda
3个回答

4
更新:我睡了一晚上,然后意识到我的方法都是错误的。
以下是一个可用的例子。它检查三个位置以确保不会错过滚动条出现:
1. 当页面加载时 2. 当添加新内容时 3. 当用户滚动时
在我的测试环境中,点击两次添加按钮正好等于屏幕高度,因此该按钮并不总是消失。 我添加了ionScrollEnd检查来提供额外的捕获方式。
您可以删除代码中散布的console.log,我将其留下来以帮助您理解发生了什么。
示例页面:
<ion-header>
  <ion-toolbar>
    <ion-title>
      Scrollbar Test
    </ion-title>
  </ion-toolbar>
</ion-header>

<ion-content [scrollEvents]="true" (ionScrollEnd)="onScrollEnd()">
  <div class="ion-padding">
    <p *ngFor="let item of itemList">{{ item }}</p>

    <ion-button *ngIf="!hasScrollbar" (click)="addMoreItemsButtonClick(5)">Load more items</ion-button>
  </div>

  <ion-infinite-scroll (ionInfinite)="loadMoreItems($event)">
    <ion-infinite-scroll-content loadingSpinner="crescent"></ion-infinite-scroll-content>
  </ion-infinite-scroll>
</ion-content>

<ion-footer>
  <ion-toolbar>
    <ion-title>
      Ionic footer
    </ion-title>
  </ion-toolbar>
</ion-footer>

示例代码:

import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';
import { IonContent } from '@ionic/angular';

@Component({
  selector: 'app-scrollheight',
  templateUrl: './scrollheight.page.html',
  styleUrls: ['./scrollheight.page.scss'],
})
export class ScrollheightPage implements OnInit {

  public hasScrollbar: Boolean = false;

  @ViewChild(IonContent) private content: IonContent;

  itemList: string[] = [];

  constructor() { }

  ngOnInit() {
    // check at startup
    this.checkForScrollbar();
  }

  ionViewWillEnter() {
    this.incrementItemList(5);
  }

  addMoreItemsButtonClick(quantity: number) {
    this.incrementItemList(quantity);

    // check after pushing to the list
    this.checkForScrollbar();
  }

  onScrollEnd() {
    // check after scrolling
    this.checkForScrollbar();
  }

  incrementItemList(times: number) {
    for (let i = 1; i <= times; i++) {
      this.itemList.push(`Lorem ipsum dolor sit amet consectetur adipisicing elit. Quia placeat nam sapiente iusto eligendi`);
    }
  }

  loadMoreItems(event: any) {
    setTimeout(() => {
      this.incrementItemList(15);

      event.target.complete();
    }, 1000);
  }

  checkForScrollbar() {
    this.content.getScrollElement().then((scrollElement) => {
      console.log("checking for scroll bar");
      console.log({scrollElement});
      console.log({scrollHeight: scrollElement.scrollHeight});
      console.log({clientHeight: scrollElement.clientHeight});
      this.hasScrollbar = (scrollElement.scrollHeight > scrollElement.clientHeight);
      console.log({hasScrollBar: this.hasScrollbar});
    });
  }
}

我现在已经用一个可行的版本替换了我的答案。 - rtpHarry
@nunoarruda 这解决了问题吗?当我终于弄明白时,我真的很高兴。很想知道它是否对你有用。在编码的前几天,我实际上在午餐时感到很紧张,因为我无法理解它,哈哈。 - rtpHarry
1
不完全相同,但它帮助我找到了适合我的使用情况的正确解决方案。非常感谢! - nunoarruda

2

在rtpHarry的帖子(谢谢!)的帮助下,我最终找到了一个适合这种情况的正确解决方案:

home.page.html

<ion-content>
  <div class="ion-padding">
    <p *ngFor="let item of itemList">{{ item }}</p>

    <!--
      '*ngIf' removes the button from the DOM and changes the size of 'ion-content' which
      is problematic in some scenarios so I toggle the visibility CSS property instead
    -->
    <ion-button [style.visibility]="hasScrollbar ? 'hidden' : 'visible'" (click)="incrementItemList(5)">Load more items</ion-button>
  </div>

  <ion-infinite-scroll (ionInfinite)="loadMoreItems($event)">
    <ion-infinite-scroll-content loadingSpinner="crescent"></ion-infinite-scroll-content>
  </ion-infinite-scroll>
</ion-content>

home.page.ts

import { Component, ViewChild, HostListener } from '@angular/core';
import { IonContent } from '@ionic/angular';

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})
export class HomePage {

  hasScrollbar = false;

  itemList: string[] = [];

  @ViewChild(IonContent, {static: false}) private content: IonContent;

  // checks if there's a scrollbar when the user resizes the window or zooms in/out
  @HostListener('window:resize', ['$event'])
  onResize() {
    this.checkForScrollbar();
  }

  constructor() {}

  ionViewWillEnter() {
    this.incrementItemList(5);
  }

  incrementItemList(times: number) {
    for (let i = 1; i <= times; i++) {
      this.itemList.push(`Lorem ipsum dolor sit amet consectetur adipisicing elit. Quia placeat nam sapiente iusto eligendi`);
    }

    this.checkForScrollbar();
  }

  loadMoreItems(event: any) {
    setTimeout(() => {
      this.incrementItemList(15);
      event.target.complete();
    }, 1000);
  }

  async checkForScrollbar() {
    const scrollElement = await this.content.getScrollElement();
    this.hasScrollbar = scrollElement.scrollHeight > scrollElement.clientHeight;
  }

}

0
请通过从@angular/core导入“NgZone”来使用它。 以下是示例代码。
.ts
import { Component, OnInit, ViewChild, NgZone } from '@angular/core';
@Component({
  selector: 'app-selector',
  templateUrl: './app.page.html',
  styleUrls: ['./app.page.scss'],
})
export class App implements OnInit {
@ViewChild("listingContent") listingContent;
public hasScrollbar: Boolean = false;
public itemList:Array<any> = [];
    constructor(private zone: NgZone) {}

    scrollHandler(event) {
        this.zone.run(()=>{
            if (event.detail.scrollTop > (document.documentElement.clientHeight + 1)) {
                this.hasScrollbar = true;
            } else {
                this.hasScrollbar = false;
            }
        });
    }
}

.html

<ion-header no-border></ion-header>
<ion-content #listingContent padding-top (ionScroll)="scrollHandler($event)" scroll-events="true">
<div class="ion-padding">
    <p *ngFor="let item of itemList">{{ item }}</p>

    <ion-button *ngIf="!hasScrollbar" (click)="addMoreItemsButtonClick(5)">Load more items</ion-button>
  </div>

</ion-content>

希望这可以帮到您。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接