🎯 目标
实现一个通用的卡片展示动画组件 SlideFadeCard
,适用于:
-
页面元素淡入淡出 + 滑动进出动画组合
-
可设置从左/右/上/下滑入方向
-
可控制进入与离开时的动画时长与曲线
-
适用于消息气泡、弹出提示、动态加载内容
🧱 动画结构示意
⬅️ [卡片内容] → 从左滑入 + 渐显
...
⏹️ 删除 → 渐隐 + 向右滑出
🧰 组件实现:SlideFadeCard.ets
export type SlideDirection = 'left' | 'right' | 'top' | 'bottom'
@Component
export struct SlideFadeCard {
@Prop show: boolean = true
@Prop direction: SlideDirection = 'bottom'
@Prop duration: number = 300
@Prop offset: number = 40 // 初始偏移像素
@Slot content: () => void
build() {
const offsetMap = {
left: { x: -this.offset, y: 0 },
right: { x: this.offset, y: 0 },
top: { x: 0, y: -this.offset },
bottom: { x: 0, y: this.offset }
}
const target = offsetMap[this.direction]
Column()
.opacity(this.show ? 1 : 0)
.translate({
x: this.show ? 0 : target.x,
y: this.show ? 0 : target.y
})
.animateTo({
duration: this.duration,
curve: Curve.EaseInOut
}) {
this.content()
}
}
}
📦 使用示例
@Entry
@Component
struct DemoSlideFadeCard {
@State visible: boolean = true
build() {
Column({ space: 20 }).padding(20) {
Button(this.visible ? '隐藏卡片' : '显示卡片')
.onClick(() => this.visible = !this.visible)
SlideFadeCard({
show: this.visible,
direction: 'left',
duration: 400
}) {
Column()
.padding(16)
.backgroundColor('#F1F9FF')
.borderRadius(12)
.shadow({ radius: 4, color: '#0000001a' }) {
Text('📬 新消息提示:你有一条未读消息').fontSize(14).fontColor('#333')
}
}
}
}
}
✨ 可扩展能力建议
能力 | 说明 |
---|---|
动画完成回调 | 可添加 onEnterDone / onExitDone 生命周期回调 |
支持透明背景过渡 | 配合全屏 Modal 实现弹窗渐入渐出 |
滑入延迟 / 批量并行动画 | 设置 delay 控制多个组件顺序进入 |
组合使用其他动效 | 与旋转、缩放、颜色渐变等组合出复杂 UI 动态场景 |
📘 下一篇预告
第3篇:【HarmonyOS 5.0.0 或以上】构建点赞动画组件 LikeBurst:支持心形跳动 / 粒子爆炸 / 点赞数增长动效