Angular项目中用CSS/Bootstrap实现答题结果淡入、整题3秒后淡出动画
答题交互动画实现方案
实现逻辑
- 给整道题套外层容器,用于控制整体淡出效果
- 优化原有滑入动画,新增透明度变化实现淡入效果
- 新增淡出动画类,控制整道题消失后自动折叠占位空间
- TS中新增定时器,按需求时序触发淡出操作,同时兼容多次点击场景
代码修改
HTML代码
<!-- 整道题外层容器,控制整体显隐和淡出动画 --> <div [class.fade-out]="!showQuestion" *ngIf="showQuestion"> <a (click)="checkAnswer(1)">Elephant</a> <br> <a (click)="checkAnswer(2)">GOAT</a><br> <a (click)="checkAnswer(13)">Crow</a> <br><br><br> <div class="slideRight" *ngIf="flag === false"> CORRECT </div> <div class="slideRight" *ngIf="flag === true"> INCORRECT </div> </div>
CSS代码
.slideRight { animation-name: slideRightFadeIn; -webkit-animation-name: slideRightFadeIn; animation-duration: 0.5s; -webkit-animation-duration: 0.5s; animation-timing-function: ease-in-out; -webkit-animation-timing-function: ease-in-out; /* 答题结果短暂延迟后展示 */ animation-delay: 0.5s; -webkit-animation-delay: 0.5s; /* 动画前后保持对应状态 */ animation-fill-mode: both; -webkit-animation-fill-mode: both; display: inline-block; } /* 整合滑入+淡入效果 */ @keyframes slideRightFadeIn { 0% { transform: translateX(-150%); opacity: 0; } 100% { transform: translateX(0%); opacity: 1; } } @-webkit-keyframes slideRightFadeIn { 0% { -webkit-transform: translateX(-150%); opacity: 0; } 100% { -webkit-transform: translateX(0%); opacity: 1; } } /* 整道题淡出动画 */ .fade-out { animation: fadeOut 0.3s ease-in-out forwards; -webkit-animation: fadeOut 0.3s ease-in-out forwards; } @keyframes fadeOut { 0% { opacity: 1; } 100% { opacity: 0; visibility: hidden; height: 0; margin: 0; padding: 0; overflow: hidden; } } @-webkit-keyframes fadeOut { 0% { opacity: 1; } 100% { opacity: 0; visibility: hidden; height: 0; margin: 0; padding: 0; overflow: hidden; } }
TS代码
import { Component, VERSION } from '@angular/core'; @Component({ selector: 'my-app', templateUrl: './app.component.html', styleUrls: [ './app.component.css' ] }) export class AppComponent { name = 'Angular ' + VERSION.major; flag : boolean | undefined; // 控制整道题显隐 showQuestion = true; // 存储定时器,避免多次点击重复触发 private fadeTimer: any; checkAnswer(select : number){ if (this.fadeTimer) clearTimeout(this.fadeTimer); // 原答题判断逻辑保持不变 this.flag = select === 1 || select === 2; // 总等待时长 = 0.5s延迟展示 + 0.5s动画时长 + 3s结果停留 = 4s this.fadeTimer = setTimeout(() => { this.showQuestion = false; }, 4000); } }
内容的提问来源于stack exchange,提问作者Illep
相关产品推荐
相关产品推荐

