我正在尝试实现与 Facebook 中可用的功能类似的功能,即如果您滚动了新闻提要,按下硬件后退按钮会将您带到列表顶部。
为此,我认为相信canDeactivate将Router Guards是正确的方法。
但我无法找到检查页面是否已滚动的方法。
我已经尝试过window.pageYOffset,但这总是返回 0,在 Guard 中访问 ViewChild 总是返回 null。
谁能指导如何实现这一目标?
我正在尝试实现与 Facebook 中可用的功能类似的功能,即如果您滚动了新闻提要,按下硬件后退按钮会将您带到列表顶部。
为此,我认为相信canDeactivate将Router Guards是正确的方法。
但我无法找到检查页面是否已滚动的方法。
我已经尝试过window.pageYOffset,但这总是返回 0,在 Guard 中访问 ViewChild 总是返回 null。
谁能指导如何实现这一目标?
有两种方法可以帮助您。
首先,从 Ionic 4 开始,您可以使用以下Platform功能注册您的后退按钮处理程序:
this.platform.backButton.subscribeWithPriority(999990, () => {
//alert("back pressed");
});
其次,您可以使用 Ionic 4 的更多功能,称为scrollEvents.
我已经在其他答案中解释了如何使用此功能:
希望这会让你朝着正确的方向前进。
我认为最后一个答案应该可以解决您的大部分问题,所以是这样的:
Freaky Jolly 有一个教程解释如何滚动到 X/Y 坐标。
首先,您需要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>
在代码中,您需要使用 a@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 */
}
}