【问题标题】:Add a scroll to top button (Ionic 2 | Typescript)添加滚动到顶部按钮(Ionic 2 | Typescript)
【发布时间】:2026-02-03 17:05:01
【问题描述】:

大家好,我正在尝试添加“滚动到顶部按钮”。实现以下内容:

1.当用户向下滚动时显示按钮。 2.当用户向上滚动时隐藏按钮。 3.如果点击按钮,则滚动到顶部并隐藏按钮。 对如何使它正确的任何建议?

非常感谢

【问题讨论】:

  • 您可能应该向我们展示一些代码,以便我们更好地帮助您。

标签: cordova typescript angular ionic2


【解决方案1】:

当你在一个组件中有一个组件时,你可能无法在内部组件中获取内容。那就是说我必须获取上部元素并调用滚动。

在我的情况下,当转到下一张幻灯片时,我必须在下一张幻灯片的顶部。

 const element = document.querySelector(".slide-zoom");
      setTimeout(() => { if(element) element.scrollIntoView(true) }, 200); 

【讨论】:

    【解决方案2】:

    你可以试试这个。希望对你有帮助

    import { Component, ViewChild } from '@angular/core';
    
    import { Content } from 'ionic-angular';
    
    @Component({...})
    
    export class MyPage{
    
      @ViewChild(Content) content: Content;
    
      scrollToTop() {
    
        this.content.scrollToTop();
      }
    
    }
    

    【讨论】:

    • 请考虑为这个答案添加一些解释,而不仅仅是代码。以及需要修复格式。
    【解决方案3】:

    在 adriancarriger 代码的帮助下,我尝试了以下方法将 Div 元素设置为 Top 并且成功了。 下面是我的代码

    HTML

    <div  #Innholdtext >
    <p> add your contents here to set scroll top </>
    </div>
    

    app.component.ts

    import { Component, OnInit,  ViewChild, ElementRef } from '@angular/core';
    export class app implements OnInit {
    
    @ViewChild('Innholdtext') private hovedInnhold : ElementRef;
        private scrollElement; 
    }
    
       ngOnInit() {
      this.scrollElement = this.hovedInnhold.nativeElement;
            this.scrollElement.addEventListener("click", () =>{
                this.hovedInnhold.nativeElement.scrollTop = 0
            });
    }
    

    【讨论】:

      【解决方案4】:

      adriancarriger简化scrollToTop()

      import { Component, ViewChild } from '@angular/core';
      import { Content } from 'ionic-angular';
      
      @Component({...})
      export class MyPage{
        @ViewChild(Content) content: Content;
      
        scrollToTop() {
          this.content.scrollToTop();
        }
      }
      

      来源:http://ionicframework.com/docs/v2/api/components/content/Content/

      【讨论】:

        【解决方案5】:

        Plunker Demo

        要完成这项工作,您需要:

        • 创建一个将scroll-content 元素滚动到顶部的函数
        • 跟踪scroll-content的滚动位置
        • 使用滚动到顶部按钮上的*ngIf 可在scroll-content 达到特定阈值后有条件地显示。

        滚动到顶部功能

        我调整了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);
        

        追踪scroll-content位置

        此示例使用窗口高度作为显示滚动到顶部按钮的阈值,如下所示:

        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>
        

        全组件 Typescript

        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://*.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>
        

        【讨论】:

        • woooow 非常感谢您的专业回答,但我遇到了一个小错误:例外:错误:未捕获(承诺):TypeError:无法读取未定义的属性“firstChild”
        • this.ionScroll = this.myElement.nativeElement.children[0].firstChild;解决了问题