WordPress站点滚动时缩小Logo及菜单栏的技术实现问询
Great job getting your logo's shrink-on-scroll functionality up and running! Extending this to your menu bar is straightforward—we'll just reuse your existing scroll event logic and add corresponding CSS for the menu. Here's how to do it:
Step 1: Define CSS for the Menu Bar
First, add styles for both the default state and the scrolled state of your menu bar. Adjust properties like padding, height, or font-size based on how you want the menu to shrink:
/* Default menu styles */ .menuclass { height: 80px; padding: 15px 20px; transition: all 0.5s linear; /* Smooth transition for all modified properties */ } /* Scrolled menu styles */ .menu-scroll { height: 50px; padding: 8px 20px; transition: all 0.5s linear; } /* Keep your existing logo styles */ .logoclass { width: 100%; transition: width 0.5s linear; } .scroll { margin-top: -10px; width: 55%; transition: width 0.5s linear; }
Step 2: Update the JavaScript to Target Both Logo and Menu
Modify your existing scroll event handler to select the menu bar element and toggle its classes alongside the logo. Replace #menubar with your actual menu bar's ID or class selector (you can find this using your browser's developer tools):
<script type="text/javascript"> window.onscroll = () => { const nav = document.querySelector('#logoid'); const menu = document.querySelector('#menubar'); // Swap this with your menu's actual selector if (this.scrollY <= 250) { nav.className = 'logoclass'; menu.className = 'menuclass'; } else { nav.className = 'scroll'; menu.className = 'menu-scroll'; } }; </script>
Key Tips for Smooth Implementation
- Preserve Existing Classes: If your menu already has other CSS classes applied (like WordPress default menu classes), use
classList.add()andclassList.remove()instead of overwritingclassNameto avoid breaking existing styles. Example:if (this.scrollY <= 250) { nav.classList.remove('scroll'); nav.classList.add('logoclass'); menu.classList.remove('menu-scroll'); menu.classList.add('menuclass'); } else { nav.classList.remove('logoclass'); nav.classList.add('scroll'); menu.classList.remove('menuclass'); menu.classList.add('menu-scroll'); } - Tweak CSS Values: Adjust
height,padding, or evenfont-sizein the.menu-scrollclass to match your site's design—this ensures the menu shrink feels cohesive with the logo's animation.
This approach keeps your code aligned with your existing implementation, ensuring both the logo and menu shrink in perfect sync as users scroll.
内容的提问来源于stack exchange,提问作者Anson

