简介
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的值可以设置不同的返回顶端控件按钮出现需要滚动的屏幕距离。