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

使用@keyframes实现汉堡菜单动画时无法播放关闭动画如何解决?

完全可以基于你现有的实现思路解决,核心是给非激活状态补充反向动画即可,无需大幅修改原有逻辑。

核心修改点

  1. 给三条横线的默认样式补充必要的初始定位属性,同时新增反向关键帧动画,对应菜单关闭时的过渡效果
  2. 将第二条线的透明度过渡移到默认类上,保证加/删类时都能触发过渡
  3. 新增初始化类避免页面加载时误触发反向动画

完整修改后代码

CSS代码

*{
    margin: 0px;
    padding: 0px;
    box-sizing: border-box;
}

body{
    background-color: black;
}

.burger{
    position: absolute;
    top:50%;
    left:50%;
    transform: translate(-50%,-50%);
}

.burger div{
    background-color: white;
    height: 5px;
    width: 45px;
    margin: 5px;
    position: relative;
    top: 0;
    bottom: 0;
}
/* 避免初始化时触发反向动画 */
.burger.is-initialized .line1{
    animation: top-reverse 0.3s ease-in both;
}
.burger.is-initialized .line2{
    transition: opacity 0.3s ease-out;
}
.burger.is-initialized .line3{
    animation: bottom-reverse 0.3s ease-in both;
}

.line1-active{
    top: 10px;
    animation: top 0.3s ease-in both !important;
}

.line2-active{
    opacity: 0;
}

.line3-active{
    bottom: 10px;
    animation: bottom 0.3s ease-in both !important;
}

@keyframes top{
    0%{
        top: 0px;
    }
    33%{
        top: 10px;
    }
    66%{
        transform: rotate(0deg);
    }
    100%{
        transform: rotate(45deg);
    }
}

@keyframes bottom{
    0%{
        bottom: 0px;
    }
    33%{
        bottom: 10px;
    }
    66%{
        transform: rotate(0deg);
    }
    100%{
        transform: rotate(-45deg);
    }
}
/* 新增反向动画 */
@keyframes top-reverse{
    0%{
        transform: rotate(45deg);
    }
    33%{
        transform: rotate(0deg);
    }
    66%{
        top: 10px;
    }
    100%{
        top: 0px;
    }
}

@keyframes bottom-reverse{
    0%{
        transform: rotate(-45deg);
    }
    33%{
        transform: rotate(0deg);
    }
    66%{
        bottom: 10px;
    }
    100%{
        bottom: 0px;
    }
}

JS代码

const Close = () =>{
    const burger = document.querySelector('.burger');
    const line1 = document.querySelector('.line1');
    const line2 = document.querySelector('.line2');
    const line3 = document.querySelector('.line3');
    // 新增初始化类,避免加载时误触发动画
    burger.classList.add('is-initialized');

    burger.addEventListener('click', () =>{
        line1.classList.toggle('line1-active');
        line2.classList.toggle('line2-active');
        line3.classList.toggle('line3-active');
    });
}

Close();

HTML代码无需修改。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 02:15:03