如何用Tailwind CSS实现下拉菜单高度动画(React+Next.js)
问题:Tailwind+React+Next.js响应式导航栏高度平滑过渡失效
我正在用TailwindCSS、React和Next.js开发副业项目,需要实现一个响应式导航栏:当屏幕尺寸达到Tailwind定义的sm规格时显示汉堡菜单,点击图标后菜单要从height:0平滑过渡到max-h-40。目前代码里的过渡效果没生效,希望帮忙排查问题。
代码:navbar.tsx
"use client"; import Image from "next/image"; import Link from "next/link"; import { useState } from "react"; import logo from "../public/finallang_favicon.ico"; export default function Navbar() { const [showMenu, setShowMenu] = useState(false); const toggleMenu = () => { setShowMenu(!showMenu); }; return ( <div> <nav className="flex items-center justify-between flex-grow w-auto py-3 text-center border-b px-9 sm:w-auto"> <div className="flex items-center justify-center flex-shrink-0 sm:mr-6"> <Link href="/"> <Image src={logo} alt="Logo" width={48} height={48} /> </Link> </div> <div className="hidden text-sm sm:block"> <Link href="#" className="block mt-4 sm:mr-4 text-slate-900 hover:text-slate-700 sm:mt-0 sm:inline-block"> About </Link> <Link href="#" className="block mt-4 sm:mr-4 text-slate-900 hover:text-slate-700 sm:mt-0 sm:inline-block"> Blog </Link> <Link href="#" className="block mt-4 text-slate-900 hover:text-slate-700 sm:mt-0 sm:inline-block"> Contact Me </Link> </div> <div> <button className="hidden px-4 py-2 text-sm leading-none rounded text-slate-100 hover:text-white sm:inline-block bg-brand"> Download </button> <button onClick={toggleMenu} aria-label="Toggle navigation menu" className="text-gray-400 align-middle sm:hidden hover:text-gray-900 focus:ring-2 rounded-md"> <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth={2} stroke="currentColor" className="w-6 h-6"> <path strokeLinecap="round" strokeLinejoin="round" d="M3.75 6.75h16.5M3.75 12h16.5m-16.5 5.25h16.5" /> </svg> </button> </div> </nav> {showMenu && ( <div className={`${showMenu ? "max-h-40" : "h-0"} text-sm text-center sm:hidden transition-all duration-500 ease-in-out overflow-hidden`}> <Link href="/about" className="block mt-4 text-slate-900 hover:text-slate-700"> About </Link> <Link href="/blog" className="block mt-4 text-slate-900 hover:text-slate-700"> Blog </Link> <Link href="/contact" className="block mt-4 text-slate-900 hover:text-slate-700"> Contact Me </Link> </div> )} </div> ); }
已尝试的方案
- 在
tailwind.config.js中添加height: "height"到transitionProperty配置 - 给下拉菜单添加
overflow-hidden类名 - 在下拉菜单的类中切换使用
transition-all和transition-[height]
当前表现
点击汉堡菜单时,下拉菜单直接显示/隐藏,没有平滑的高度过渡效果,无法实现预期的动画过程。
期望效果
下拉菜单在500ms内从height:0平滑过渡到max-h-40,使用ease-in-out过渡时序函数。
内容的提问来源于stack exchange,提问作者ZTatman
相关产品推荐
相关产品推荐

