使用max-height结合transition实现折叠菜单动画,通过切换expanded类控制max-height从0到300px变化,配合overflow:hidden实现平滑展开收起效果。

使用 CSS transition 制作折叠菜单动画,关键是控制元素的高度或 max-height 配合过渡效果,实现平滑展开与收起。下面介绍一种常见且实用的做法。
直接对 height: auto 做 transition 是无效的,因为 auto 不是一个具体数值。解决方法是使用 max-height 来模拟高度变化。
基本思路:
.menu {
max-height: 0;
overflow: hidden;
transition: max-height 0.3s ease-out;
}
.menu.expanded {
max-height: 500px;
}
菜单结构通常包含一个按钮和一个下拉容器:
立即学习“前端免费学习笔记(深入)”;
<button onclick="toggleMenu()">菜单</button> <div class="menu" id="menu"> <a href="#">选项 1</a> <a href="#">选项 2</a> <a href="#">选项 3</a> </div>
用 JavaScript 切换类名:
function toggleMenu() {
const menu = document.getElementById('menu');
menu.classList.toggle('expanded');
}
让动画更自然,可以注意以下几点:
will-change: max-height;
<style>
.menu {
max-height: 0;
overflow: hidden;
transition: max-height 0.3s ease-out;
background: #f8f8f8;
}
.menu a {
display: block;
padding: 10px;
text-decoration: none;
color: #333;
}
.menu.expanded {
max-height: 300px;
border-top: 1px solid #ddd;
}
</style>
<button onclick="toggleMenu()">展开菜单</button>
<div class="menu" id="menu">
<a href="#">首页</a>
<a href="#">关于</a>
<a href="#">联系</a>
</div>
<script>
function toggleMenu() {
const menu = document.getElementById('menu');
menu.classList.toggle('expanded');
}
</script>
基本上就这些。关键在于理解 max-height + overflow + transition 的组合用法,避免尝试对 height: auto 做动画。这种方式兼容性好,无需 JS 计算高度,适合大多数折叠菜单场景。
以上就是如何用css transition制作折叠菜单动画的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号