1. 程式人生 > >ionic2長列表返回頂端控制元件的一個簡單實現

ionic2長列表返回頂端控制元件的一個簡單實現

簡介

ionic2有ion-infinite-scroll元件可以讓我們方便的實現移動端的分頁查詢邏輯(上拉載入更多操作)。可是在列表很長的時候,我們還需要一個可以快速返回列表頂部的空間。

實現

#scroll-to-top.component.html

<ion-fab [hidden]="!fabshow" tappable (click)="scollToTop();">
    <button ion-fab icon-only class="el-stt-button">
        <ion-icon name="arrow-dropup"
>
</ion-icon> </button> </ion-fab>

#scroll-to-top.component.scss

.el-stt-button{
    position:fixed !important;
    z-index: 999;
    bottom: 20px;
    right:20px;
    height:40px;
    width:40px;
    border-radius: 50%;
    background:#f4f4f4;
    &.activated{
        background
: #8d8d8d } .icon{ color:#6b6b6b; font-size:40px; } }

#scroll-to-top.component.ts

import { Component, Input, ApplicationRef } from "@angular/core";
import { Content } from "ionic-angular";

@Component({
    selector: "scroll-to-top",
    templateUrl: "scroll-to-top.component.html"
}) export class ScrollToTopComponent { fabshow: boolean = false; //開始出現返回頂部按鈕的距離(Content.scrollHeight的指定倍數,預設為2) @Input("dis") _dis: number = 2; constructor(private _content: Content, private applicationRef:ApplicationRef) { } ngAfterViewInit() { this._content.ionScroll.subscribe(content => { let sh = content.contentHeight, st = content.scrollTop; if (!this.fabshow && st > sh * this._dis) { //翻了指定的頁數,顯示置頂按鈕 this.fabshow = true; //立即開始dom-value檢查 this.applicationRef.tick(); } else if (this.fabshow && st < sh) { //翻到頂部了,隱藏置頂按鈕 this.fabshow = false; //立即開始dom-value檢查 this.applicationRef.tick(); } }); } scollToTop() { this._content.scrollToTop(); } }

使用

<ion-content>
    <ion-list>
    </ion-list>
    <scroll-to-top dis="2"></scroll-to-top>
</ion-content>

改變dis的值可以設定不同的返回頂端控制元件按鈕出現需要滾動的螢幕距離。