ionic-framework - 服务/保护中的 Ionic 4 滚动位置
问题描述
我正在尝试实现与 Facebook 中可用的功能类似的功能,即如果您滚动了新闻提要,按下硬件后退按钮会将您带到列表顶部。
为此,我认为相信canDeactivate
将Router Guards
是正确的方法。
但我无法找到检查页面是否已滚动的方法。
我已经尝试过window.pageYOffset
,但这总是返回 0,在 Guard 中访问 ViewChild 总是返回 null。
谁能指导如何实现这一目标?
解决方案
有两种方法可以帮助您。
首先,从 Ionic 4 开始,您可以使用以下Platform
功能注册您的后退按钮处理程序:
this.platform.backButton.subscribeWithPriority(999990, () => {
//alert("back pressed");
});
其次,您可以使用 Ionic 4 的更多功能,称为scrollEvents
.
我已经在其他答案中解释了如何使用此功能:
- 如何检测 ion-content 是否有滚动条?
- 如何在 Ionic 4 的离子含量组件中检测到滚动已结束?
- ionic 4 - 使用 typeScript 滚动到我的 webView 上的 x,y 坐标
希望这会让你朝着正确的方向前进。
我认为最后一个答案应该可以解决您的大部分问题,所以是这样的:
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 */
}
}
推荐阅读
- java - AWT 机器人类问题
- xcode - 什么可能导致 macOS 应用程序在视网膜 macOS 上呈现所有模糊
- python - 对两个未知因变量使用curve_fit,这种方法正确吗?
- java - Splitpane 中 ScrollPane 中的 Gridbaglayout
- firebase - Firebase Admin SDK 是否执行任何缓存?
- java - Jasper Reports - 如何将参数传递给 ResourceRenderer.getInstance()?
- python-3.x - 根据年份创建新的 DataFrame 列
- javascript - React useEffect 无限循环
- python - 从 Python Flask 中的变量指定模板名称(使用 Flask Frozen)
- c# - c# Functions, Invalid token 'bool' in class, struct, or interface member declaration