大家好我想添加“滚动到顶部按钮”.实现以下内容: 1.当用户向下滚动时显示按钮. 2.当用户向上滚动时隐藏按钮. 3.如果点击按钮,则滚动到顶部并隐藏按钮. 有关如何正确的方式的任何
1.当用户向下滚动时显示按钮.
2.当用户向上滚动时隐藏按钮.
3.如果点击按钮,则滚动到顶部并隐藏按钮.
有关如何正确的方式的任何建议?
非常感谢
Plunker Demo要完成这项工作,您需要:
>创建一个将scroll-content元素滚动到顶部的函数
>跟踪滚动内容的滚动位置
>滚动到顶部按钮时使用* ngIf,以在滚动内容达到特定阈值后有条件地显示.
滚动到顶部功能
我调整了this SO answer以应用于scroll-content元素
scrollToTop(scrollDuration) { let scrollStep = -this.ionScroll.scrollTop / (scrollDuration / 15); let scrollInterval = setInterval( () => { if ( this.ionScroll.scrollTop != 0 ) { this.ionScroll.scrollTop = this.ionScroll.scrollTop + scrollStep; } else { clearInterval(scrollInterval); } }, 15);
跟踪滚动内容位置
此示例使用窗口高度作为显示滚动到顶部按钮的阈值,如下所示:
this.ionScroll.addEventListener("scroll", () => { if (this.ionScroll.scrollTop > window.innerHeight) { this.showButton = true; } else { this.showButton = false; } });
按钮Html
<button *ngIf="showButton" (click)="scrollToTop(1000)">Scroll Top</button>
完整组件打字稿
import { NavController } from 'ionic-angular/index'; import { Component, OnInit, ElementRef } from "@angular/core"; @Component({ templateUrl:"home.html" }) export class HomePage implements OnInit { public ionScroll; public showButton = false; public contentData = []; constructor(public myElement: ElementRef) {} ngOnInit() { // Ionic scroll element this.ionScroll = this.myElement.nativeElement.children[1].firstChild; // On scroll function this.ionScroll.addEventListener("scroll", () => { if (this.ionScroll.scrollTop > window.innerHeight) { this.showButton = true; } else { this.showButton = false; } }); // Content data for (let i = 0; i < 301; i++) { this.contentData.push(i); } } // Scroll to top function // Adapted from https://stackoverflow.com/a/24559613/5357459 scrollToTop(scrollDuration) { let scrollStep = -this.ionScroll.scrollTop / (scrollDuration / 15); let scrollInterval = setInterval( () => { if ( this.ionScroll.scrollTop != 0 ) { this.ionScroll.scrollTop = this.ionScroll.scrollTop + scrollStep; } else { clearInterval(scrollInterval); } }, 15); } }
完整组件Html
<ion-navbar primary *navbar> <ion-title> Ionic 2 </ion-title> <button *ngIf="showButton" (click)="scrollToTop(1000)">Scroll Top</button> </ion-navbar> <ion-content class="has-header" #testElement> <div padding style="text-align: center;"> <h1>Ionic 2 Test</h1> <div *ngFor="let item of contentData"> test content-{{item}} </div> </div> </ion-content>