Ionic如何创建自定义展开标题组件

来源:互联网 发布:sass 22.0 for mac 编辑:程序博客网 时间:2024/05/16 10:32

自定义组件

我开始构建一个简单的实现,最后一个自定义组件如下所示:


自动获取标题高度,然后当标题滚动时,可扩展标题缩减开始被切断的任何元素将会消失(并退回到再次出现空间的位置)。

创建组件

ionic g component super-header

修改super-header.ts 

oldHeight: number;  newHeight: number;  @Input() scrollContent: any;  constructor(private zone: NgZone, private rend2: Renderer2, private el: ElementRef) {}  ngOnInit(): void {    if (!this.oldHeight) {      //获取标签高度      this.oldHeight = this.el.nativeElement.clientHeight;    }    this.zone.run(() => {      //监听滚动事件      this.scrollContent.ionScroll.subscribe((ev) => {        ev.domWrite(() => {          //减掉滚动的高度          this.newHeight = this.oldHeight - ev.scrollTop;          if (this.newHeight < 0) {            //滚动高度超出标签高度设为0px (隐藏标签)            this.newHeight = 0;          }          this.handlerEl();        });      });    });  }    handlerEl() {    //设置标签高度    this.rend2.setStyle(this.el.nativeElement, 'height', this.newHeight + 'px');    //查找子标签    let subs = this.el.nativeElement.children;    //设置显示隐藏效果    for (let sub of subs) {      let totalHeight = sub.offsetTop + sub.clientHeight;      if (totalHeight > this.newHeight && !sub.isHidden) {        sub.isHidden = true;        this.rend2.setStyle(sub, 'opacity', '0.8');      } else if (totalHeight <= this.newHeight && sub.isHidden) {        sub.isHidden = false;        this.rend2.setStyle(sub, 'opacity', '1');      }    }
修改super-header.scss

super-header {    display: block;    transform: translate3d(0, 0, 0);    transition: 500ms ease-out;    background-color: map-get($colors, primary) !important;    overflow: hidden;}
修改super-header.html
<ng-content></ng-content>
  • scrollContent是我们在收听滚动事件的区域,以确定标题何时展开和缩小。
  • OnInit组件初始化的时候监听滚动事件。
  • 我们循环遍历组件所有子项,并检查元素的底部是否已被标题遮住。通过结合offsetTop与clientHeight每个元素的,我们能够制定出其中元件的底部实际上是相对于头部。
  • 通过设置isHidden属性跟踪当前元件是否显示。出于性能原因,我们希望尽可能避免DOM更新。
  • 通过domWrite是对dom的高效修改。
  • 设置overflow属性在此处非常重要,否则组件不可见时,标题中的内容将会溢出到内容区域中。

将组件添加到模板

<ion-header no-border>    <super-header [scrollContent]="content">        <ion-item>            <ion-label>                <ion-icon name="search"></ion-icon>            </ion-label>            <ion-input type="text"></ion-input>        </ion-item>    </super-header>    <ion-navbar>        <ion-title>Home</ion-title>    </ion-navbar></ion-header><ion-content fullscreen #content>    <ion-list>        <ion-item *ngFor="let item of items">            {{item}}        </ion-item>    </ion-list></ion-content>

重要的部分是我们在其中使用标签<super-header>,我们还设置了一个#content在该<ion-content>区域上调用的局部变量,并使用scrollContent输入将其传递到组件中。将fullscreen属性添加到该<ion-content>区域也很重要,以便标题正确显示。

我们对DOM进行高效的写入,因此它将在设备上运行良好,并且在应用程序中的任何位置也很容易配置和重用。

源码分享地址



原创粉丝点击