Ionic自定义按钮动画触发所有按钮



我正试图在Ionic应用程序中实现一个动画收藏夹按钮,但遇到了一些问题。

该按钮在单击时按预期工作,但它也会触发每隔一个按钮播放动画。每次加载页面时,动画也会在所有按钮上播放。我怀疑我添加活动类的ngClass语句是在页面加载帖子时被触发的,并且在添加收藏夹时从可观察到的数据更新时再次被触发。

<ion-button class="favourite" fill="clear" size="small" (click)="toggleFavourite( post, user.userId )">
<ion-icon [ngClass]="{'active': post.favourites && post.favourites[user.userId] ? true : false}" class="heart"></ion-icon>
</ion-button>

css:

.heart {
width: 100px;
height: 100px;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%) scale(0.9);
background: url('/assets/images/heart.png') no-repeat;
background-position: 0 0;
cursor: pointer;
animation: fave-heart 1s steps(28);
}
.heart.active {
background-position: -2800px 0;
transition: background 1s steps(28);
}
@keyframes fave-heart {
0% {
background-position: 0 0;
}
100% {
background-position: -2800px 0;
}
}

我做了更多的测试,发现每次更新posts变量时都会触发按钮动画。帖子作为可观察的内容返回,因此每当页面加载时,以及当用户喜欢帖子时,它都会更新,这样我就可以更新按钮。然而,我添加了一个按钮,它调用getPosts((函数(如下(,并且每次单击都会触发动画。


<ion-button (click)="getPosts(limit)">click</ion-button>
getPosts(limit){
return new Promise((resolve) => {
this.postsService.getPosts(limit).subscribe(data => {
this.posts = data.reverse()
let key = data[data.length - 1].$key;
if (this.lastId === key){
this.hasMoreData = false;
}
resolve(data);
});
});
}

我做了更多的研究,找到了一种更好的方法。这种方法使用Ionic 5动画,这样我就可以在选择时瞄准被点击播放动画的元素的id。

&.heart {
width: 100px;
height: 100px;
position: absolute;
transform: scale(0.9);
background: url('/assets/images/heart.png') no-repeat;
background-position: 0 0;
cursor: pointer;
}
&.heart.active {
background-position: -2800px 0;
}
<ion-col *ngFor="let post of postList ; let i = index;">
<ion-button (click)="toggleFavourite( post, user.userId, '#favourite' + i )">
<ion-icon [id]="'favourite'+i" class="heart" color="pink" [ngClass]="{'active': post.favourites && post.favourites[user.userId] ? true : false}"></ion-icon>
</ion-button>
</ion-col>
import { AnimationController } from '@ionic/angular';
constructor(private animationCtrl: AnimationController){ }
animateForward(elementId){
const animation = this.animationCtrl
.create()
.addElement(document.querySelector(elementId))
.duration(1000)
.iterations(1)
.easing( 'steps(28, end)')
.keyframes([
{ offset: 0, backgroundPosition: '0 0' },
{ offset: 1, backgroundPosition: '-2800px 0' }
])
animation.play()
}
animateBack(elementId){
const animation = this.animationCtrl
.create()
.addElement(document.querySelector(elementId))
.duration(300)
.iterations(1)
.easing( 'steps(28, end)')
.keyframes([
{ offset: 0, transform: 'scale(0.9)' },
{ offset: 0.7, transform: 'scale(1)' },
{ offset: 1, transform: 'scale(0.9)' }
])
animation.play()
}

最新更新