ionic2中實(shí)現(xiàn)sticky功能,在ios中使用的是position:sticky屬性哩罪,但是這個(gè)屬性在大部分的瀏覽器中并不支持,android瀏覽器也一樣不支持攒读。在安卓中使用fixed屬性片排。
我在做這個(gè)功能的時(shí)候花了大量的時(shí)間寨腔,主要還是因?yàn)閷?duì)ionic2的不熟悉造成的。下面給出我的爬坑之路率寡。
第一坑:使用Directive
理論上來(lái)說(shuō)使用directive是最好的方法迫卢,但是本人實(shí)力有限實(shí)現(xiàn)不了。
首先執(zhí)行:ionic g directive stick,會(huì)在項(xiàng)目中生成一個(gè)components文件夾冶共,里面有一個(gè)stick.ts文件:
import { Directive } from '@angular/core';
/*
Generated class for the Stick directive.
See https://angular.io/docs/ts/latest/api/core/index/DirectiveMetadata-class.html
for more info on Angular 2 Directives.
*/
@Directive({
selector: '[stick]' // Attribute selector
})
export class Stick {
constructor() {
console.log('Hello Stick Directive');
}
}
具體用法<element stick></element>
在使用directive的時(shí)候注意不能在page對(duì)應(yīng)的ts文件中通過(guò)directives:[Stick]來(lái)使用乾蛤,而是應(yīng)該在app.modules.ts中去聲明
@NgModule({
declarations: [
MyApp,
Stick
]
})
然后就可以在所有頁(yè)面去應(yīng)用這個(gè)directive了。
第二坑:在ionic2中使用原生js進(jìn)行scroll的監(jiān)聽
1捅僵、使用angular2提供的HostListener
@HostListener('window:scroll',['$event'])
handleScrollEvent(e) {
console.log('scrool');
}
//這種方式監(jiān)聽不到scroll事件但是可以監(jiān)聽到click事件
2家卖、使用window.onscroll
window.onscroll = (e)=>{
console.log('scrool');
}
//這樣的方式也監(jiān)聽不到滾動(dòng)事件
3、使用document.addEventListener
document.addEventListener('scroll', (e) => {
console.log('scrool');
}, true);
這種方式是可以監(jiān)聽到滾動(dòng)事件的庙楚,但是在這里面沒有辦法獲取到滾動(dòng)時(shí)距頂部的距離上荡,也沒有辦法使用
最終在多番嘗試之后使用的是angular2提供的addScrollListener方法
import { Component, ViewChild, ElementRef,Renderer } from '@angular/core';
import { NavController, MenuController,Content } from 'ionic-angular';
@ViewChild(Content) content:Content;
@ViewChild('item') stick;
ionViewDidLoad() {
this.content.addScrollListener((event)=>{
let top = event.target.scrollTop;
let domTop = this.stick._elementRef.nativeElement.offsetTop;
if(top>domTop){
//this.render.setElementClass(this.stick._elementRef.nativeElement,'stick-item',true)
this.stick._elementRef.nativeElement.classList.add('stick-item')
}else{
this.stick._elementRef.nativeElement.classList.remove('stick-item')
}
})
}
使用以下的方法即可實(shí)現(xiàn)滾動(dòng)的時(shí)候獲取距離頂部的距離了。但是要使用這個(gè)方法馒闷,必須在頁(yè)面對(duì)應(yīng)的ts文件中酪捡,而不能寫成directive,但是按道理是可以寫進(jìn)directive的,但是本人水平有限纳账,望高人不吝賜教逛薇。
但是在ionic rc.4中addScrollListener又不適用了,而是需要使用以下方法塞祈,
this.content.ionScroll.subscribe(($event: any) => {
let top = $event.scrollTop;
}
然后添加stick-item這個(gè)class后就可以寫相應(yīng)的樣式了
--scss文件---
ion-content {
ion-list {
ion-item-divider.stick-item {
background: red;
position: fixed;
top: 44px;
}
}
}
<ion-content padding>
<ion-list>
<ion-item-divider #item>Item1</ion-item-divider>
<ion-item *ngFor="let item1 of items1">
{{item1.name}}
</ion-item>
<ion-item-divider>Item2</ion-item-divider>
<ion-item *ngFor="let item2 of items2">
{{item2.name}}
</ion-item>
</ion-list>
</ion-content>
這里使用#item標(biāo)識(shí)然后用@ViewChild獲取金刁。