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

Angular点击小色块替换对应大色块功能实现问题求助

解决方案

核心思路:将原来每个颜色独立的显示状态,改为维护一个当前激活颜色变量,确保同一时间仅显示一个大div,点击新颜色时直接替换激活状态即可。

修改后代码

app.component.ts

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  colors = ['red','yellow','pink','green'];
  // 用单个变量存储当前激活的颜色,初始为null表示无激活状态
  activeColor: string | null = null;
  title = 'project';

  toggleBigDiv(color:string){
    // 点击当前激活的颜色则关闭大div,否则切换为该颜色的大div
    this.activeColor = this.activeColor === color ? null : color;
  }
}

app.component.html

<!-- 循环渲染小颜色块 -->
<div *ngFor="let color of colors" class="color-div" [ngClass]="color" (click)="toggleBigDiv(color)">
  {{color}}
</div>

<!-- 单独渲染大div,根据当前激活颜色控制显示与样式 -->
<div *ngIf="activeColor" class="big-div" [ngClass]="activeColor">
  Big {{activeColor}} Div
</div>

app.component.css(无需修改)

.red{
    background-color: red;
}
.yellow{
    background-color: yellow;
}
.pink{
    background-color: pink;
}
.green{
    background-color: green;
}
.big-div{
    position: absolute;
    left : 110px;
    width:300px;
    height:300px;
   
}

修改说明

  1. 移除了原有的shownDivs对象,改用activeColor变量跟踪当前选中的颜色,从根源避免多个大div同时显示的问题
  2. 将大div从循环的小div内部抽离为全局元素,确保页面中始终只有一个大div实例
  3. 调整点击事件逻辑:点击已激活的颜色时关闭大div,点击其他颜色时直接切换激活状态,实现替换效果

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 16:12:42