【问题标题】:Ionic 4 Scroll Position in Service/Guard服务/保护中的 Ionic 4 滚动位置
【发布时间】:2020-01-11 12:10:35
【问题描述】:

我正在尝试实现类似于 Facebook 中可用的功能,即如果您滚动了新闻提要,按下硬件返回按钮会将您带到列表顶部。

为此,我认为Router Guards 中的canDeactivate 是正确的方法。

但我无法找到检查页面是否已滚动的方法。

我尝试过window.pageYOffset,但这总是返回 0,在 Guard 中访问 ViewChild 总是返回 null。

谁能指导如何实现这一目标?

【问题讨论】:

  • 您需要具体说明您的标签,因为不同的 ionic 版本做的事情非常不同。我已经根据您的问题标题 ionic4 对其进行了清理。

标签: ionic-framework ionic4


【解决方案1】:

有两种方法可以帮助您。

首先,从 Ionic 4 开始,您可以使用 Platform 功能注册您的后退按钮处理程序:

https://www.freakyjolly.com/ionic-4-overridden-back-press-event-and-show-exit-confirm-on-application-close/

this.platform.backButton.subscribeWithPriority(999990,  () => {
   //alert("back pressed");
});

其次,您可以使用 Ionic 4 的更多功能,称为scrollEvents

我已经在其他答案中解释了如何使用此功能:

希望这会让你朝着正确的方向前进。

我认为最后一个答案应该可以解决您的大部分问题,所以是这样的:

Freaky Jolly 有一个tutorial explaining how to scroll to an X/Y coord

首先,您需要scrollEvents 上的ion-content

<ion-header>
  <ion-toolbar>
    <ion-title>
      Ion Content Scroll
    </ion-title>
  </ion-toolbar>
</ion-header>

<ion-content [scrollEvents]="true">
 <!-- your content in here -->
</ion-content>

在代码中您需要使用@ViewChild 来获取对ion-content 的代码引用,然后您可以使用它的ScrollToPoint() api:

import { Component, ViewChild } from '@angular/core';
import { Platform, IonContent } from '@ionic/angular';

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})
export class HomePage {
    // This property will save the callback which we can unsubscribe when we leave this view
    public unsubscribeBackEvent: any;
    @ViewChild(IonContent) content: IonContent;

    constructor(
        private platform: Platform
    ) { }

    //Called when view is loaded as ionViewDidLoad() removed from Ionic v4
    ngOnInit(){
        this.initializeBackButtonCustomHandler();
    }


    //Called when view is left
    ionViewWillLeave() {
        // Unregister the custom back button action for this page
        this.unsubscribeBackEvent && this.unsubscribeBackEvent();
    }

    initializeBackButtonCustomHandler(): void {
        this.unsubscribeBackEvent = this.platform.backButton.subscribeWithPriority(999999,  () => {
            this.content.scrollToPoint(0,0,1500);
        });
        /* here priority 101 will be greater then 100 
        if we have registerBackButtonAction in app.component.ts */
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-10-14
    • 2019-07-11
    • 2019-08-04
    • 1970-01-01
    • 2020-03-12
    • 1970-01-01
    • 1970-01-01
    • 2011-03-22
    相关资源
    最近更新 更多