【发布时间】:2019-11-28 13:53:14
【问题描述】:
我正在从 firebase 读取一系列运动器材,并将它们作为离子卡显示在屏幕上。
每个离子卡都分配有一个元素 ID,我想获取特定离子卡的 yOffset,并在加载屏幕时直接滚动到该离子卡。
yOffset 似乎总是返回 0,即使该特定元素不在屏幕上……您必须向下滚动到它。
ngOnInit(){
this.matchService.getMatches().get().then(matchSnapshot => {
this.matches= [];
matchSnapshot.forEach(snap => {
this.matches.push ({
id: snap.id,
date: snap.data().date,
team: snap.data().team,
home: snap.data().home,
away: snap.data().away,
homeScore: snap.data().homeScore,
awayScore: snap.data().awayScore,
});
return false;
});
var elementID =
this.getElementIdOfFixtureClosestToToday(this.matches);
setTimeout(()=>{this.scrollToYOffsetOfElement(elementID);},3000);
});
}
this.getElementIdOfFixtureClosestToToday 成功返回我想要的元素 ID
private scrollToYOffsetOfElement(element: string){
let yOffset = document.getElementById(element).offsetTop;
console.log("yOffset = " + yOffset);
this.content.scrollToPoint(0,yOffset,300);
}
我的 HTML 代码
<ion-content #content>
<ion-card *ngFor="let match of matches; let i = index" tappable
routerLink="/../match-details-standard/{{match.id}}" >
<ion-card-content id='{{i}}'>
<ion-grid >
<ion-row>
<ion-col></ion-col>
<ion-col></ion-col>
<ion-col class="team" col-3>{{match?.team}}</ion-col>
<ion-col></ion-col>
<ion-col></ion-col>
</ion-row>
<!-- matchNotPlayed: If the match has been played then I
don't want to show the day which it was played -->
<ion-row *ngIf="match?.homeScore != ''; else matchNotPlayed">
<ion-col></ion-col>
<ion-col></ion-col>
<ion-col col-3>{{match?.date.seconds * 1000 | date:'d MMM yy' }}</ion-col>
<ion-col></ion-col>
<ion-col></ion-col>
</ion-row>
<ng-template #matchNotPlayed>
<ion-row> {{match?.date.seconds * 1000 | date:'EE d MMM yy' }}</ion-row>
</ng-template>
<!-- matchNotPlayed: End -->
<!-- noScoreReceived: If the match has been played and
scores updated then display scores else show 'v' between team names-->
<ion-row *ngIf="match?.homeScore != ''; else
noScoreReceived" border="solid">
<ion-col col-2>{{match?.home}}</ion-col>
<ion-col col-1 style="text-align: right">
{{match?.homeScore}}</ion-col>
<ion-col col-1> - </ion-col>
<ion-col col-1 style="text-align: left">
{{match?.awayScore}}</ion-col>
<ion-col col-2> {{match?.away}}</ion-col>
</ion-row>
<ng-template #noScoreReceived>
<ion-row>
<ion-col col-2>{{match?.home}}</ion-col>
<ion-col col-1></ion-col>
<ion-col col-1> v </ion-col>
<ion-col col-1></ion-col>
<ion-col col-2> {{match?.away}}</ion-col>
</ion-row>
</ng-template>
<!-- noScoreReceived -->
<ion-row> {{match?.date.seconds * 1000 | date:'h:mm a' }}
</ion-row>
</ion-grid>
</ion-card-content>
</ion-card>
</ion-content>
【问题讨论】:
-
你试过 element.getBoundingClientRect() 吗?
-
这也带回了 0。我开始认为问题出在我正在动态创建离子卡这一事实。
-
将我的 html 文件添加到问题中
标签: typescript ionic-framework scroll offset