如何为汉堡菜单hover动画添加延迟且不影响开合动画?
解决汉堡菜单hover动画延迟不影响开合动画的问题
你的问题核心在于hover状态的动画规则没有排除.open状态,导致即使按钮处于打开状态,hover的动画延迟仍然会干扰开合的过渡效果。我们可以通过更精准的CSS选择器来分离两种状态的动画逻辑,只在按钮未打开时应用hover的滑动延迟动画。
修改方案
- 使用
:not(.open)伪类限制hover动画的触发条件,确保只有按钮未处于打开状态时,hover才会触发带延迟的滑动动画。 - 简化CSS动画的定义,避免重复设置
animation属性,提升代码可读性。
修改后的完整代码
HTML(无需改动)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="toggle-button"> <span></span> <span></span> <span></span> </div>
JavaScript(无需改动)
$(document).ready(function() { $('.toggle-button').click(function() { $(this).toggleClass('open') }); });
CSS(关键修改部分已标注)
.toggle-button { width: 24px; height: 29px; top: 50%; left: 64px; position: fixed; cursor: pointer; outline: none; overflow: hidden; z-index: 101; } /* 关键修改:仅在按钮未打开时应用hover滑动动画 */ .toggle-button:not(.open):hover span:nth-child(1) { animation: spanSlide 1s linear; } .toggle-button:not(.open):hover span:nth-child(2) { animation: spanSlide 1s linear 0.1s; } .toggle-button:not(.open):hover span:nth-child(3) { animation: spanSlide 1s linear 0.2s; } @keyframes spanSlide { 0% { transform: translateX(0%) } 50% { transform: translateX(100%) } 51% { transform: translateX(-100%) } 100% { transform: translateX(0%) } } .toggle-button span { display: block; position: relative; height: 1px; width: 100%; background: black; opacity: 1; left: 0; transform: rotate(0deg); transition: .5s ease-in-out; z-index: 102; } .toggle-button span:nth-child(1) { top: 1px; transform-origin: left center; } .toggle-button span:nth-child(2) { top: 11px; transform-origin: left center; } .toggle-button span:nth-child(3) { top: 22px; transform-origin: left center; } .toggle-button.open span:nth-child(1) { transform: rotate(45deg); background-color: blue; /* 修正原代码中#blue的无效颜色值 */ width: 40px; animation: none; } .toggle-button.open span:nth-child(2) { width: 0%; opacity: 0; transition: .1s; background-color: blue; animation: none; } .toggle-button.open span:nth-child(3) { transform: rotate(-45deg); background-color: blue; width: 40px; animation: none; }
为什么这样有效?
:not(.open)伪类确保hover动画只会在按钮没有open类时触发,当按钮打开后,hover不会再触发滑动动画,自然不会有延迟干扰开合的过渡效果。- 去掉了多余的
.toggle-button:hover span的animation-name设置,避免了动画属性的重复定义,让代码更清晰。 - 顺便修正了你CSS里的小错误:
#blue是无效的颜色值,改为了合法的blue。
内容的提问来源于stack exchange,提问作者lumi
相关产品推荐
相关产品推荐

