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

使用NgFor渲染Tailwind手风琴时内容无法展开的问题

问题解决:Tailwind手风琴无法展开内容且结构异常

你的代码存在几个关键问题,导致手风琴无法展开内容,同时出现多个独立手风琴的状态:

错误点分析

  • 标题ID未动态绑定:所有标题的ID固定为accordion-collapse-heading-1,导致内容区域的aria-labelledby无法正确关联对应标题,直接破坏手风琴的交互逻辑
  • 核心属性不匹配:虽然对部分属性做了动态绑定,但最关键的标题唯一标识未动态生成,组件无法识别对应的内容展开区域

修正后的代码

<div id="accordion-collapse" data-accordion="collapse">
  <div *ngFor="let post of posts; index as i">
    <!-- 动态生成唯一标题ID -->
    <h2 id="accordion-collapse-heading-{{i}}">
      <button type="button"
        class="flex items-center justify-between w-full p-5 font-medium rtl:text-right text-gray-500 border border-b-0 border-gray-200 rounded-t-xl focus:ring-4 focus:ring-gray-200 dark:focus:ring-gray-800 dark:border-gray-700 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-800 gap-3"
        attr.data-accordion-target="#accordion-collapse-body-{{i}}" 
        aria-expanded="false"
        attr.aria-controls="accordion-collapse-body-{{i}}">
        <span>{{post.title}}</span>
        <svg data-accordion-icon class="w-3 h-3 shrink-0" aria-hidden="true"
          xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 10 6">
          <path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
            d="M9 5 5 1 1 5" />
        </svg>
      </button>
    </h2>
    <div id="accordion-collapse-body-{{i}}" class="hidden" 
         attr.aria-labelledby="accordion-collapse-heading-{{i}}">
      <div class="p-5 border border-b-0 border-gray-200 dark:border-gray-700 dark:bg-gray-900">
        <p class="mb-2 text-gray-500 dark:text-gray-400">{{post.content}}</p>
      </div>
    </div>
  </div>
</div>

关键修改说明

  1. 动态生成唯一ID:将h2的id改为accordion-collapse-heading-{{i}},确保每个标题拥有唯一标识,和内容区域的aria-labelledby形成正确关联
  2. 调整初始状态:把aria-expanded默认设为false,符合手风琴常规的初始收起状态(若需要默认展开特定项,可通过条件判断动态绑定该属性)
  3. 图标状态修正:移除rotate-180类,默认显示向下箭头,Flowbite会在展开时自动旋转图标

另外需确认已正确引入Flowbite的JavaScript文件(Tailwind CSS本身不提供手风琴交互逻辑,Flowbite基于Tailwind实现了这类组件),可通过CDN或模块化导入方式加载脚本。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 21:58:24