簡體   English   中英

ionic2-滾動以觸發

[英]ionic2 - scroll to trigger

我只想在頁面滾動到特定點時顯示ion-header

HTML

<ion-header  *ngIf="headered"><!--use ngif to trigger-->
  <ion-navbar>
    some content
  </ion-navbar>
</ion-header>

因此它將通過滾動觸發:

TS

import { ..., Content } from 'ionic-angular';

...
@ViewChild(Content) content:Content;

headered = false;
...
ngAfterViewInit() {
    this.content.addScrollListener(this.onPageScroll);
}

onPageScroll(event) {
    console.log(event.target.scrollTop);
    if(event.target.scrollTop > 640){
      this.headered = true;
      console.log(this.headered);///<-- this did trigger when scroll more than 640
    }else{
      this.headered = false;
    }
}

我確實在控制台中得到了true的顯示,但是標題沒有顯示。 我通過添加一個調用此功能的按鈕再次對其進行測試:

toggleHeader(){
  this.headered = (this.headered == false) ? true : false;
}

標題確實按縱橫比顯示和隱藏。

為什么滾動事件無法顯示標題? 我該如何解決?

Update01

我試過了:

scrollCount = 0;

...

onPageScroll(event) {
    this.scrollCount = event.target.scrollTop;
console.log(this.scrollCount);///<-- this give me reading
}

///then use ngDoCheck to detect:

ngDoCheck(){
console.log(this.scrollCount);///<-- this always get 0.
}

如您所見,在onPageScroll()我可以閱讀,但我沒有閱讀。 我懷疑這與@ViewChild(Content) content:Content; ionic2他們的文檔中建議。

就像您說的,看看“ 內容-離子文檔”,我發現:

調整()

告訴內容重新計算其尺寸。 在動態添加頁眉,頁腳或制表符之后,應調用此方法。

因此,由於您通過執行以下操作獲取內容的實例

@ViewChild(Content) content:Content;

請嘗試以下操作:

onPageScroll(event) {
    console.log(event.target.scrollTop);
    if(event.target.scrollTop > 640){
      this.headered = true;
      console.log(this.headered);///<-- this did trigger when scroll more than 640
    }else{
      this.headered = false;
    }

    // Update the content since the header was shown / hidden
    this.content.resize();
}

編輯

由於onPageScroll被調用了很多次,並且只需要在scrollTop高於640 並且沒有顯示標題時(或當scrollTop小於或等於640 並且顯示標題時)更新內容。讓我們稍微修改一下代碼:

onPageScroll(event) {
    console.log(event.target.scrollTop);
    if(event.target.scrollTop > 640 && !this.headered){
      // If the scrollTop is higher than 640 and the header is hidden, we need to show it (this prevent trying to update the header status also when scrollTop is 642, 643, and so on
      this.headered = true;
      console.log(this.headered);///<-- this did trigger when scroll more than 640

      if(this.content) {
        // Update the content
        this.content.resize();
      }
    }else if(event.target.scrollTop <= 640 && this.headered){
      // If the scrollTop is lower or equal than 640 and the header is visible, we need to hide it (this prevent trying to update the header status also when scrollTop is 639, 638, and so on
      this.headered = false;

      if(this.content) {
        // Update the content
        this.content.resize();
      }
    } 
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM