我想计算 IonContent 的当前滚动百分比(它是一个 Ionic + React 应用程序)
页面布局如下所示:
<IonPage>
<IonHeader>
<IonToolbar>
<IonButtons slot="start">
<IonMenuButton />
</IonButtons>
<IonTitle>Page</IonTitle>
</IonToolbar>
</IonHeader>
<IonContentid="main-content"
scrollEvents={true}
onIonScroll={(ev) => {
// ToDo: calculate scroll percentage
console.log(ev.detail.scrollTop);
}}>
{// very long custom component
}
<IonFooter>
<IonLabel>Footer </IonLabel>
</IonFooter>
</IonContent>
</IonPage>
从 IonScroll 事件中,我可以读出scrollTop,它似乎是当前的滚动位置。
现在我需要获取 IonContent 的最大滚动高度。
相关问题:
- finding the maximum scroll position of a page
- Cross-Browser Method to Determine Vertical Scroll Percentage in Javascript
- how to calculate height of scroll content
第一个问题中接受的答案似乎提供了最完整的方法,通过选择滚动高度值的最大值:
var limit = Math.max( document.body.scrollHeight, document.body.offsetHeight,
document.documentElement.clientHeight, document.documentElement.scrollHeight, document.documentElement.offsetHeight );
我还添加了以下内容来扩展它:
document.scrollingElement.scrollHeight
问题:
在我的场景中,这些值的最大值约为 660。但是 ev.detail.scrollTop
的日志输出高达 680.76
。
我已连接调试检查器并尝试从控制台滚动,以查看滚动值在 660 左右时会发生什么。当从 660 滚动到 680 时,我仍然可以看到内容移动:
document.getElementById('main-content').scrollToPoint(0, 680);
如何找到最大滚动坐标?
最佳答案
我想我找到了解决方案:
onIonScroll={async (ev) => {
const elem = document.getElementById("ion-content-id");
// the ion content has its own associated scrollElement
const scrollElement = await ( elem as any).getScrollElement()
const scrollPosition = ev.detail.scrollTop;
const totalContentHeight = scrollElement.scrollHeight;
const viewportHeight = elem.offsetHeight;
const percentage = scrollPosition / (totalContentHeight - viewportHeight);
console.log(percentage);
}}
我不明白为什么会引入这种不兼容性。是否可以将 IonContent
的 scrollElement
与 document.scrollingElement
连接起来? The standard is still a draft但在所有主要浏览器中实现(IE 除外)。
关于javascript - 如何获得 ionic 内容的最大滚动高度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61886891/