如何在ionic 4中隐藏滚动标题?

ben*_*-we 4 ionic-framework ionic4

我想知道如何通过向下滚动页面来隐藏 Ionic 4 中的标题,并在向上滚动时重新显示它。

我找到了很多关于如何做到这一点的解决方案,但它们都无法正常工作或已过时。

所以我收集了我能找到的所有信息来提供这个答案。

ben*_*-we 18

多亏了这个视频,我才开始工作。

首先调用ionic g directive directives/hide-header. 您当然可以替换directive/hide-header为您自己的路径和名称。

hide-header.directive.ts

import { Directive, HostListener, Input, OnInit, Renderer2 } from '@angular/core';
import { DomController } from '@ionic/angular';

@Directive({
    selector: '[appHideHeader]'
})
export class HideHeaderDirective implements OnInit {

    @Input('header') header: any;

    private lastY = 0;

    constructor(
        private renderer: Renderer2,
        private domCtrl: DomController
    ) { }

    ngOnInit(): void {
        this.header = this.header.el;
        this.domCtrl.write(() => {
            this.renderer.setStyle(this.header, 'transition', 'margin-top 700ms');
        });
    }

    @HostListener('ionScroll', ['$event']) onContentScroll($event: any) {
        if ($event.detail.scrollTop > this.lastY) {
            this.domCtrl.write(() => {
                this.renderer.setStyle(this.header, 'margin-top', `-${ this.header.clientHeight }px`);
            });
        } else {
            this.domCtrl.write(() => {
                this.renderer.setStyle(this.header, 'margin-top', '0');
            });
        }

        this.lastY = $event.detail.scrollTop;
    }

}
Run Code Online (Sandbox Code Playgroud)

之后,在您的模板中:

<ion-header #header>
    <ion-toolbar><ion-title>Test</ion-title></ion-toolbar>
</ion-header>
<ion-content scrollEvents="true" appHideHeader [header]="header">
</ion-content>
Run Code Online (Sandbox Code Playgroud)

注意scrollEvents,appHideHeader和[header]属性!最后一个将标题元素作为参数,在本例中为#header。


大多数代码与视频中显示的相同。我更改了host-property@Directive并使用了更新的HostListener。

如果要在多个指令中使用该指令,则需要创建一个SharedModule。

为此,请使用ng g module shared. 在那之后,加入HideHeaderDirective到declarations与exports阵列。

shared.module.ts

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { HideHeaderDirective } from './directives/hide-header.directive';


@NgModule({
    declarations: [HideHeaderDirective],
    exports: [HideHeaderDirective],
    imports: [
        CommonModule
    ]
})
export class SharedModule {}

Run Code Online (Sandbox Code Playgroud)

现在将共享模块添加到要在其中使用指令的所有模块中。

注意:您不能将指令导入app.module.ts并在子模块中使用它!您必须在要在其中使用指令的每个直接模块中导入共享模块。

我当前的node,npm和版本ionic:

版本

  • 标题有时会闪烁 (2认同)
  • 我对此进行了扩展,添加了一个额外的输入属性“scrollThreshold”(“动画开始之前从顶部以像素为单位的最小滚动偏移量。”),我仅在 iOS 上设置该属性,以避免弹跳滚动以及与“ion-”组合使用时出现的问题。复习`。可以在这里找到:https://gist.github.com/klemensz/2a91bbe764bf4b0046b47840b6bef429 使用示例:`&lt;ion-content rollEvents="true" appHideHeader [header]="segmentedSwitch" [scrollThreshold]="plt.is(' ios') ? 50 : 0"&gt;`。 (2认同)