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

如何为汉堡菜单实现display:none到display:flex的过渡动画效果?

问题原因

  1. CSS transition 不支持 display 属性的状态切换,你用 display: none 隐藏导航、切换到 display: flex 显示的过程是瞬间完成的,无法触发过渡效果。
  2. transition 属性只写在了切换后的 .change 类中,没有定义在导航的基础样式 .nav 上,状态切换时过渡逻辑不完整。
  3. 定位、盒模型相关属性分写在两个类中,切换时会出现属性突变,打断过渡。

修复方案

直接修改你的CSS代码即可:

.navigation {
  display: flex;
  background-color: rgb(46, 46, 46);
  /* 新增:作为内部绝对定位元素的父级定位基准 */
  position: relative;
}

.nav {
  padding: 0;
  margin: 0 20px;
  /* 删掉display:none,改用支持过渡的属性控制显隐 */
  opacity: 0;
  visibility: hidden;
  transform: translateY(-15px); /* 初始状态向上偏移,过渡更有层次 */
  position: absolute;
  top: 0;
  left: 0;
  /* 过渡属性写在基础类,双向切换都生效 */
  transition: all .5s ease-out;
}

.change {
  background-color: #2e2e2e;
  margin: 0;
  font-size: .8rem;
  width: 100%;
  display: flex;
  flex-direction: column;
  /* 显示状态的属性 */
  opacity: 1;
  visibility: visible;
  transform: translateY(0);
}

修复后点击汉堡菜单就能看到平滑的过渡效果,你也可以调整transform的偏移值、过渡时长来匹配你要的动效节奏。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 13:06:11