簡述:實現商品詳情頁頂部導航顯示的明暗效果。在頁面頂部是不顯示導航,隨着滑動導航漸明。並且滑動到相應模塊是導航的狀態也隨之變化,點擊導航時頁面滑動到指定位置。
第一:需要在組件中引入相關模塊;
import { Component, NgZone, ViewChild } from '@angular/core';
import { IonicPage, NavController, NavParams, PopoverController, ModalController, Content } from 'ionic-angular';
第二:如果只是監聽頁面滑動,只需要標注@ViewChild(Content) content: Content;就可以了。
export class ProductPage {
@ViewChild(Content) content: Content; //括號中的值在html頁面中標注的時候,名稱不能其他屬性相同。如該文件已經有一個pnavs的變量,則會報錯。 @ViewChild('pnavs') sticknavs; @ViewChild('evaluate') stickevaluate; @ViewChild('detail') stickdetail;
}
附加:如果要監聽頁面的某個元素,並對其進行操作的話,在html文件中如下標記即可:
<ion-header>
<!--wechatHidden-->
<ion-navbar wechatHidden>
<ion-title>商品詳情</ion-title>
</ion-navbar>
<ion-grid #pnavs class="product-navs" [style.opacity]="navsOpacity" [ngClass]="{activetop: isShowTopNavs}">
<ion-row>
<ion-col (click)="changeNavs(i,true)" [ngClass]="{active: isNavActive==i}" *ngFor="let nav of navs;let i=index"> {{nav.title}} </ion-col>
</ion-row>
</ion-grid>
</ion-header>
<ion-content>
<ion-list #evaluate class="product-evaluate">
<ion-list-header>
<ion-icon name="ribbon"></ion-icon>寶貝評價<span *ngIf="pInfo.evaluateTotalCount>0">({{pInfo.evaluateTotalCount}})</span></ion-list-header>
</ion-list>
<ion-list #detail class="product-imgs">
<!--[ngClass]="{active: isNavActive==1}"-->
<ion-list-header>
<ion-icon name="images"></ion-icon>商品詳情</ion-list-header>
</ion-list>
</ion-content>
第三:在組件加載完成的方法之內,對頁面的滑動進行監聽;
ionViewDidLoad() { this.content.ionScroll.subscribe(($event: any) => { this.ngzone.run(() => {//如果在頁面滑動過程中對數據進行修改,頁面是不會重構的。所以在對應的操作中需要使用如下方法,使頁面能夠重構。
this.eve = $event; let top = $event.scrollTop;//當前滑動的距離
this.navsOpacity = top * 0.005;//導航透明度漸變
let navoffsettop = this.sticknavs.nativeElement.offsetTop;//當前元素距離頂部的距離。
this.navs[0].anchor = navoffsettop; let evaluateoffsettop = this.stickevaluate.nativeElement.offsetTop; this.navs[1].anchor = evaluateoffsettop let detailoffsettop = this.stickdetail.nativeElement.offsetTop; this.navs[2].anchor = detailoffsettop if (top > 10) { this.isShowTopNavs = true;//是否顯示導航
if (top + 41 < evaluateoffsettop) { // 基本信息
this.changeNavs(0); } else if (top + 41 >= evaluateoffsettop && top + 41 < detailoffsettop) { //寶貝評價
this.changeNavs(1); } else if (top + 41 >= detailoffsettop) { // 商品詳情
this.changeNavs(2); } } else { this.isShowTopNavs = false; } }); }) } changeNavs(index: number, isClick?: boolean): void { this.isNavActive = index; if (isClick) { //跳轉到指定的位置
this.content.scrollTo(0,this.navs[index].anchor-40,1000); } }
補充:#標記的元素屬性讀取方式似乎與標記的元素有關(獲取頁面元素的方式Android系統和iOS系統不一樣)
but:
謹記不要試圖直接去操作頁面元素,例如我改變頁面某個元素的樣式,其實可以通過其他方法達到同樣的效果;