You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ionic5中如何使用多条件ng-class实现答题按钮样式动态切换

代码修改方案

1. 调整quiz.ts逻辑

首先在类中新增2个全局状态变量:

isAnswered = false; // 标记当前题目是否已完成作答
currentCorrectAnswer: string = ''; // 存储当前题目的正确答案

替换原有choice函数为以下版本:

choice(ans, qn)  { 
  // 已作答的题不再响应点击
  if(this.isAnswered) return;

  this.selectedItem = ans.choice;
  // 格式化当前题目正确答案存储
  this.currentCorrectAnswer = qn.corect.toString().replace(/\s/g, "");
  // 标记为已作答
  this.isAnswered = true;

  if (this.selectedItem.toString().replace(/\s/g, "") == this.currentCorrectAnswer) {
    console.log('correct');
    this.incrimentScore();
    this.textToSpeech.speak({
      text: 'correct Answer.',
      locale: 'en-US',
      rate: 0.7
    })
      .then(() =>
        console.log('Done')
      )
      .catch((reason: any) =>
        console.log(reason)
      );
  } else {
    this.textToSpeech.speak({
      text: 'you are wrong',
      locale: 'en-US',
      rate: 0.7
    })
      .then(() =>
        console.log('Done')
      )
      .catch((reason: any) =>
        console.log(reason)
      );
  }   
}

// 新增切换题目时的状态重置方法,滑动到下一题时调用即可
resetQuestionState() {
  this.isAnswered = false;
  this.selectedItem = '';
  this.currentCorrectAnswer = '';
}

2. 修改quiz.html模板的样式绑定逻辑

替换答案选项的ion-card节点代码:

<ion-card 
  (click)="choice(ans,qn, indexOfelement)"
  *ngFor="let ans of qn.Answer; let indexOfelement=index;"
  [ngClass]="{
    'correct': isAnswered && ans.choice.toString().replace(/\s/g, '') == currentCorrectAnswer,
    'wrong': isAnswered && ans.choice == selectedItem && ans.choice.toString().replace(/\s/g, '') != currentCorrectAnswer
  }"
>
  <ion-card-content>
    {{ans.choice}}
  </ion-card-content>
</ion-card>

3. 添加对应样式

在页面的scss/css文件中新增样式:

.correct {
  background-color: #2ecc71 !important;
  color: #fff !important;
}
.wrong {
  background-color: #e74c3c !important;
  color: #fff !important;
}

内容的提问来源于stack exchange,提问作者Jimmy Boaz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.19 14:45:11