Ionic2 Sticky 粘附效果

来源:互联网 发布:安卓游戏源码改端口 编辑:程序博客网 时间:2024/06/16 09:43

ionic2中实现sticky功能,在ios中使用的是position:sticky属性,但是这个属性在大部分的浏览器中并不支持,android浏览器也一样不支持。在安卓中使用fixed属性。
我在做这个功能的时候花了大量的时间,主要还是因为对ionic2的不熟悉造成的。下面给出我的爬坑之路。
第一坑:使用Directive
理论上来说使用directive是最好的方法,但是本人实力有限实现不了。
首先执行:ionic g directive stick,会在项目中生成一个components文件夹,里面有一个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的时候注意不能在page对应的ts文件中通过directives:[Stick]来使用,而是应该在app.modules.ts中去声明

@NgModule({  declarations: [    MyApp,    Stick  ]  })

然后就可以在所有页面去应用这个directive了。
第二坑:在ionic2中使用原生js进行scroll的监听
1、使用angular2提供的HostListener

      @HostListener('window:scroll',['$event'])        handleScrollEvent(e) {            console.log('scrool');        }       //这种方式监听不到scroll事件但是可以监听到click事件

2、使用window.onscroll

window.onscroll = (e)=>{console.log('scrool');}//这样的方式也监听不到滚动事件

3、使用document.addEventListener

document.addEventListener('scroll', (e) => {console.log('scrool');}, true);这种方式是可以监听到滚动事件的,但是在这里面没有办法获取到滚动时距顶部的距离,也没有办法使用

最终在多番尝试之后使用的是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')    }   })   }

使用以下的方法即可实现滚动的时候获取距离顶部的距离了。但是要使用这个方法,必须在页面对应的ts文件中,而不能写成directive,但是按道理是可以写进directive的,但是本人水平有限,望高人不吝赐教。
但是在ionic rc.4中addScrollListener又不适用了,而是需要使用以下方法,

this.content.ionScroll.subscribe(($event: any) => {         let top = $event.scrollTop; }

然后添加stick-item这个class后就可以写相应的样式了

--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标识然后用@ViewChild获取。

1 0