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

如何用Alpine.js和Tailwind CSS优化响应式导航栏避免重复链接?

当然可以合并!完全不需要重复写两遍导航链接,用Alpine.js的数据驱动和循环就能搞定,代码更简洁易维护。

修改后的完整代码

<div class="bg-gray-800 text-white xs:flex-col sm:flex p-2 font-bold" x-data="{showDropdown: false, navLinks: [
    {text: 'Link 1', href: '#'},
    {text: 'Link 2', href: '#'},
    {text: 'Link 3', href: '#'},
    {text: 'Link 4', href: '#'},
    {text: 'Link 5', href: '#'},
    {text: 'Link 6', href: '#'},
    {text: 'Link 7', href: '#'},
    {text: 'Link 8', href: '#'}
]}">
    <div class="flex flex-auto border p-2">
        <a class="flex-auto hover:text-cyan-300" href="#">Logo</a>
        <a class="hover:text-cyan-300 xs:block sm:hidden" href="#" x-on:click="showDropdown = !showDropdown" x-on:click.outside="showDropdown = false">
            <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5"
                stroke="currentColor" class="size-8 border rounded">
                <path stroke-linecap="round" stroke-linejoin="round"
                    d="M3.75 5.25h16.5m-16.5 4.5h16.5m-16.5 4.5h16.5m-16.5 4.5h16.5" />
            </svg>
        </a>
    </div>

    <!-- 合并后的导航链接容器 -->
    <div class="flex-auto border" x-show="showDropdown || $screen('sm')" :class="{'sm:flex': $screen('sm'), 'xs:flex-col': !$screen('sm')}">
        <template x-for="link in navLinks" :key="link.text">
            <div class="flex flex-auto sm:items-center sm:text-center border hover:bg-gray-50 hover:text-gray-800 p-2">
                <a class="w-full" :href="link.href" x-text="link.text"></a>
            </div>
        </template>
    </div>
</div>
<div class="p-4">
    Lorem ipsum dolor, sit amet consectetur adipisicing elit. Cumque illo excepturi asperiores accusamus facilis qui
sed! Eius quod laboriosam, adipisci esse atque totam iusto quos saepe earum blanditiis, aliquid placeat!
</div>

关键改动说明

  • 数据驱动导航项:在x-data里定义navLinks数组存储所有导航链接的文本和地址,后续增改链接只需修改数组,不用动模板
  • 单容器适配多状态:合并原有的两个导航容器,通过响应式类和Alpine判断控制显示:
    • 屏幕≥sm尺寸时,自动水平排列且始终显示
    • 屏幕<sm尺寸时,默认隐藏,点击汉堡按钮后垂直展开显示
  • 循环渲染链接:用x-for遍历数组,只写一遍链接模板,自动生成所有导航项,彻底消除代码重复
  • 修复语法问题:修正了原代码中部分<a>标签的多余引号错误

内容的提问来源于stack exchange,提问作者Javad-M

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 22:03:14