Web开发学习笔记:Ionic4中根据滚动条滚动的距离设置返回顶部按钮显示与隐藏

以下代码使用IDE:vscode; 语言模式:TypeScript

1.在HTML页 中使用悬浮按钮当做返回顶部的按钮,并绑定ion-content的ionScroll事件

<ion-content padding (ionScroll)="ionScroll()" scroll-events='true'  id='Content' >
  <!-- slot="fixed":固定在底部,使悬浮按钮不会随着页面滚动 -->
  <ion-fab id="addData_FabBtn" vertical="bottom" horizontal="end" slot="fixed">
    <ion-fab-button hidden id='BackTop' (click)="backContentTop()" size='small'>
      <ion-icon name="arrow-round-up"></ion-icon>
    </ion-fab-button>
    <ion-fab-button (click)="fabBtnClick()" size='small'>
      <ion-icon name="add"></ion-icon>
    </ion-fab-button>
  </ion-fab>
  <ion-item *ngFor="let item of test" color=""> 
    item:{{item}}  
  </ion-item>
</ion-content>

2.在对应HTML页面的ts文件中编写后端代码

2.1引入对应的依赖

import { Component, OnInit, Renderer2, ElementRef } from '@angular/core';
import { NavController, ToastController, IonContent } from '@ionic/angular';

2.2在构造函数中定义对应的声明

public test: any[]=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20];
constructor(
    public renderer2: Renderer2,
    public dbManagerService: DBManagerService,
    public elementRef: ElementRef,
    public ionContent: IonContent

  ) {
   
  }

2.3在ngOnInit方法中获取页面元素

// 初始化
  ngOnInit() {
    this.elContent = this.elementRef.nativeElement.querySelector('#Content');
    this.elBackTop = this.elementRef.nativeElement.querySelector('#BackTop');
  }

2.4获取实际滚动的元素,并根据滚动距离设置返回按钮的隐藏显示属性

ionScroll() {
    // getScrollElement():获取实际滚动发生的元素
    const scrollElement: Promise<HTMLElement> = this.elContent.getScrollElement() ;
    scrollElement.then((Element) => {
      if (Element.scrollTop > 110) { // 设置当滚动条距离顶部的距离为110时返回顶部按钮显示
        this.renderer2.removeAttribute(this.elBackTop, 'hidden');
      } else if (Element.scrollTop === 0) { // 设置当滚动条距离顶部的距离为0时返回顶部按钮隐藏
        this.renderer2.setAttribute(this.elBackTop, 'hidden', 'true');
      }
    });
  }

 

效果:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值