用CSS animation实现折叠菜单动画需通过max-height和opacity变化配合keyframes,结合JS控制类名切换状态。首先设置.menu-list默认max-height:0并隐藏溢出,定义expand和collapse两个关键帧动画分别处理展开与收起的过渡效果,其中expand从max-height:0到500px并增加透明度,collapse反之。当点击按钮时,JavaScript为.menu-list添加或移除expanded类,触发动画。为适应不同内容高度,可将max-height设为较大值如999px以兼容动态项数,同时确保overflow:hidden防止内容溢出。最终通过animation的forwards保持动画结束后的状态,实现平滑展开收起效果。

制作折叠菜单的展开动画,关键在于用 CSS 控制高度变化并配合 transition 或 animation 实现平滑效果。虽然使用 transition 更常见也更简单,但如果你希望用 CSS animation 来实现,下面是一个实用方案。
先写一个简单的折叠菜单结构:
<div class="menu">
<button class="menu-toggle">展开/收起</button>
<ul class="menu-list">
<li>菜单项 1</li>
<li>菜单项 2</li>
<li>菜单项 3</li>
</ul>
</div>
CSS 动画不能直接对 height: auto 做动画,所以需要设定一个最大高度(max-height),通过改变 max-height 触发动画。
定义两个状态的 animation:
立即学习“前端免费学习笔记(深入)”;
.menu-list {
max-height: 0;
overflow: hidden;
background: #f0f0f0;
list-style: none;
padding: 0;
margin: 0;
animation: collapse 0s forwards; /* 默认收起 */
}
<p>/<em> 展开动画 </em>/
@keyframes expand {
from { max-height: 0; opacity: 0; }
to { max-height: 500px; opacity: 1; }
}</p><p>/<em> 收起动画 </em>/
@keyframes collapse {
from { max-height: 500px; opacity: 1; }
to { max-height: 0; opacity: 0; }
}</p><p>/<em> 当添加展开类时触发展开动画 </em>/
.menu-list.expanded {
animation: expand 0.3s ease-in-out forwards;
}</p>通过 JS 添加或移除 expanded 类来触发动画:
document.querySelector('.menu-toggle').addEventListener('click', function() {
const list = document.querySelector('.menu-list');
if (list.classList.contains('expanded')) {
list.classList.remove('expanded');
} else {
list.classList.add('expanded');
}
});
点击按钮时,.expanded 类被添加,触发 expand 动画;再次点击则移除类,回到 collapse 状态。
如果菜单项数量不确定,固定 max-height 可能不够灵活。可以结合 JS 动态设置:
但若追求简洁,设一个较大的 max-height(如 999px)也能满足大多数场景,只要 overflow: hidden 能隐藏超出部分即可。
基本上就这些。用 CSS animation 做折叠菜单的核心是借助 max-height 和 opacity 配合 keyframes 实现视觉上的展开收起效果,再通过 JS 控制类名切换动画状态。不复杂但容易忽略细节,比如忘记 overflow: hidden 或 forwards 保留最终状态。
以上就是如何用css animation制作折叠菜单展开动画的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号