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

如何在TailwindCSS与Alpine.js中实现无重复内容的响应式手风琴标签组件

无重复内容的响应式手风琴标签实现(TailwindCSS + Alpine.js)

实现思路

要解决内容重复的问题,核心逻辑是仅保留单份内容节点,通过flex布局的order属性配合响应式断点控制内容的显示位置:

  • 移动端(<640px):激活标签的内容通过order属性自动排列到对应触发按钮的下方,实现手风琴展开效果
  • 桌面端(≥640px):所有内容节点的order统一设为最大值,全部排列到标签头部的下方,实现标签页效果

完整实现代码

<div class="m-1.5" x-data="{ tab : 'tab-a' }">
  <div class="flex flex-col sm:flex-row sm:flex-wrap">
    <!-- Tab A 触发按钮 -->
    <a x-on:click="tab = 'tab-a'" class="order-1 sm:order-none">
      <div 
        :class="tab === 'tab-a' ? 'sm:bg-white' : 'sm:bg-gray-200'" 
        class="sm:rounded-t-sm sm:mr-2 cursor-pointer bg-gray-200 font-bold p-1.5 pb-3 pt-3 text-gray-700 text-xs my-px sm:mb-0 w-full sm:w-max"
      >
        Tab A
      </div>
    </a>

    <!-- Tab B 触发按钮 -->
    <a x-on:click="tab = 'tab-b'" class="order-3 sm:order-none">
      <div 
        :class="tab === 'tab-b' ? 'sm:bg-white' : 'sm:bg-gray-200'" 
        class="sm:rounded-t-sm sm:mr-2 cursor-pointer bg-gray-200 font-bold p-1.5 pb-3 pt-3 text-gray-700 text-xs my-px sm:mb-0 w-full sm:w-max"
      >
        Tab B
      </div>
    </a>

    <!-- Tab C 触发按钮 -->
    <a x-on:click="tab = 'tab-c'" class="order-5 sm:order-none">
      <div 
        :class="tab === 'tab-c' ? 'sm:bg-white' : 'sm:bg-gray-200'" 
        class="sm:rounded-t-sm sm:mr-2 cursor-pointer bg-gray-200 font-bold p-1.5 pb-3 pt-3 text-gray-700 text-xs my-px sm:mb-0 w-full sm:w-max"
      >
        Tab C
      </div>
    </a>

    <!-- Tab A 内容 仅定义1次 -->
    <div 
      x-ref="containerA"
      class="order-2 sm:order-[100] w-full relative overflow-hidden max-h-0 duration-300 sm:max-h-none sm:mt-2"
      x-bind:style="tab === 'tab-a' ? 'max-height: ' + $refs.containerA.scrollHeight + 'px' : 'max-height: 0'"
      x-show="tab === 'tab-a'"
    >
      Tab A 内容,仅存在一份
    </div>

    <!-- Tab B 内容 仅定义1次 -->
    <div 
      x-ref="containerB"
      class="order-4 sm:order-[100] w-full relative overflow-hidden max-h-0 duration-300 sm:max-h-none sm:mt-2"
      x-bind:style="tab === 'tab-b' ? 'max-height: ' + $refs.containerB.scrollHeight + 'px' : 'max-height: 0'"
      x-show="tab === 'tab-b'"
    >
      Tab B 内容,仅存在一份
    </div>

    <!-- Tab C 内容 仅定义1次 -->
    <div 
      x-ref="containerC"
      class="order-6 sm:order-[100] w-full relative overflow-hidden max-h-0 duration-300 sm:max-h-none sm:mt-2"
      x-bind:style="tab === 'tab-c' ? 'max-height: ' + $refs.containerC.scrollHeight + 'px' : 'max-height: 0'"
      x-show="tab === 'tab-c'"
    >
      Tab C 内容,仅存在一份
    </div>
  </div>
</div>

关键优化说明

  • 每个标签内容仅声明一次,完全消除冗余代码
  • 通过设置奇数order给按钮、偶数order给对应内容,移动端激活时内容会自动插入到对应按钮下方
  • 桌面端所有内容的order统一设为100,全部排列到所有按钮的下方,自动实现标签页布局
  • 保留了原有的平滑展开动画,同时兼容响应式切换无卡顿

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 07:09:00