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

汉堡菜单切换器(hamburger toggler)刷新后首次点击动画失效问题求助

汉堡菜单首次点击无动画的原因及修复方案

这个问题我太熟悉啦!咱们先拆解下为啥第一次点击没动画,第二次就正常了:

问题根源

你看,你的.mainMenu默认是display: none的,当第一次点击openMenu时,你先把它的display改成flex,紧接着设置top: 0。但浏览器对display: none的元素不会计算过渡动画——因为元素之前根本不在文档流里,相当于“突然出现”,所以过渡效果直接被跳过了。

而第二次点击的时候呢?因为第一次点击后,.mainMenu的display已经是flex了,只是关闭时把top设成了-100%,元素其实还在文档流里。这时候再点击打开,修改top属性就会触发你设置的transition: top 1s ease,动画自然就正常了。

修复方案

我们只需要调整CSS和JS的逻辑,让.mainMenu始终保持在文档流里,用top属性来控制显示隐藏,而不是display:

1. 修改CSS

把.mainMenu的默认样式里的display: none去掉,改成top: -100%(默认隐藏在视口外):

.row .right nav .mainMenu {
  background-color: #ff640b;
  height: 100vh;
  /* 去掉 display: none */
  display: flex; /* 始终保持flex布局 */
  position: fixed;
  top: -100%; /* 默认隐藏在视口上方 */
  right: 0;
  left: 50%;
  z-index: 10;
  -webkit-box-orient: vertical;
  -webkit-box-direction: normal;
  -ms-flex-direction: column;
  flex-direction: column;
  -webkit-box-pack: center;
  -ms-flex-pack: center;
  justify-content: center;
  -webkit-box-align: center;
  -ms-flex-align: center;
  align-items: center;
  -webkit-transition: top 1s ease;
  transition: top 1s ease;
  list-style: none;
}

2. 简化JS代码

现在不需要再修改display属性了,只需要控制top值就行:

const mainMenu = document.querySelector(".mainMenu");
const closeMenu = document.querySelector(".closeMenu");
const openMenu = document.querySelector(".openMenu");

openMenu.addEventListener("click", () => {
  mainMenu.style.top = "0"; // 直接显示
});

closeMenu.addEventListener("click", () => {
  mainMenu.style.top = "-100%"; // 隐藏回视口外
});

这样修改后,第一次点击打开菜单时,元素本来就在文档流里,top从-100%过渡到0,动画就会正常生效啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 10:23:11