鼠标悬停图标时nav元素滑入效果异常问题求助
Solution
Key Fixes for Your Navbar Animation
Your original code had two main issues:
display: nonecan't be animated, so the navbar appeared instantly instead of sliding.- Adjacent sibling hover selectors couldn't keep the navbar visible when moving from the icon to the navbar itself.
Here's the corrected implementation that meets all your requirements:
Modified HTML
Add the JavaScript at the end of your HTML to handle hover state persistence:
<header> <div class="thing"> <img src="img/mainicon.png" class="mainicon"> <nav> <ul> <li><a class="menu" href="#">Half-Life</a></li> <li><a class="menu" href="#">Half-Life 2</a></li> <li><a class="menu" href="#">Half-Life Alyx</a></li> </ul> </nav> </div> <div class="clean"></div> </header> <script> const icon = document.querySelector('.mainicon'); const nav = document.querySelector('nav'); let isHovering = false; function showNav() { isHovering = true; nav.classList.add('show-nav'); } function hideNav() { isHovering = false; setTimeout(() => { if (!isHovering) { nav.classList.remove('show-nav'); } }, 200); } icon.addEventListener('mouseenter', showNav); icon.addEventListener('mouseleave', hideNav); nav.addEventListener('mouseenter', showNav); nav.addEventListener('mouseleave', hideNav); </script>
Modified CSS
Replace your CSS with this to enable the slide animation:
.mainicon { width: 8%; margin-left: 2%; margin-top: 2%; float: left; cursor: pointer; } .clean{ clear: both; content: "."; display: block; height: 0; line-height: 0; visibility: hidden; } nav { height: 100px; position: fixed; top: 0; left: 0; right: 0; transform: translateY(-100%); transition: transform 1s ease 0.5s; justify-content: center; align-items: center; border: 4px solid #2CBCD6; background-color: grey; text-align: center; } nav.show-nav { transform: translateY(0); } ul { padding: 0; width: 100%; } li { display: inline; font-size: 25px; } a { outline: none; text-decoration: none; display: inline-block; width: 20%; margin-right: 0.625%; text-align: center; line-height: 3; color: black; }
What Changed
- Animatable Visibility: Replaced
display: nonewithtransform: translateY(-100%)to hide the navbar off-screen above the viewport. This property is animatable. - Transition Effect: Added
transition: transform 1s ease 0.5sto create the 0.5s delay and 1-second slide animation. - Hover Persistence: JavaScript tracks hover state for both the icon and navbar. A 200ms timeout on
mouseleaveprevents the navbar from disappearing immediately when moving between the two elements. - Fixed Positioning: The navbar is fixed to the top of the screen so it slides into the correct position.
内容的提问来源于stack exchange,提问作者CookiesAreUnderrated
相关产品推荐
相关产品推荐

