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