不使用jQuery实现单页网站导航活跃锚点链接高亮
Hey Moe! Great question—implementing a fixed navigation with active section highlighting and smooth scrolling is a common need for single-page sites, and it’s totally doable with vanilla JavaScript. Let’s walk through the full solution step by step:
First, set up your fixed navigation bar and page sections. Each nav link uses an anchor tag pointing to the id of its corresponding section, and we’ll add a default active class to the Home link since that’s the starting point.
<!-- Fixed Navigation Bar --> <nav class="main-nav"> <a href="#home" class="nav-link active">Home</a> <a href="#about" class="nav-link">About</a> <a href="#contact" class="nav-link">Contact</a> </nav> <!-- Page Sections --> <section id="home" class="page-section"> <h2>Home</h2> <!-- Your home content here --> </section> <section id="about" class="page-section"> <h2>About</h2> <!-- Your about content here --> </section> <section id="contact" class="page-section"> <h2>Contact</h2> <!-- Your contact content here --> </section>
Next, style the fixed navigation, define the active link appearance, and add smooth scrolling behavior natively. We’ll also add padding to sections to prevent content from being hidden under the fixed nav.
/* Fixed Navigation */ .main-nav { position: fixed; top: 0; width: 100%; background-color: #2c3e50; padding: 1.2rem 2rem; box-shadow: 0 2px 5px rgba(0,0,0,0.1); } .nav-link { color: white; text-decoration: none; margin: 0 1.5rem; font-size: 1.1rem; transition: all 0.3s ease; } /* Active Link Highlight */ .nav-link.active { color: #3498db; font-weight: 600; border-bottom: 2px solid #3498db; } /* Page Sections */ .page-section { min-height: 100vh; padding: 7rem 2rem 2rem; /* Top padding accounts for fixed nav height */ } /* Native Smooth Scrolling */ html { scroll-behavior: smooth; }
This is the core part: we’ll listen for scroll events, check which section is currently in the viewport, and update the active nav link accordingly. No jQuery required!
// Grab all nav links and page sections const navLinks = document.querySelectorAll('.nav-link'); const sections = document.querySelectorAll('.page-section'); // Function to update active nav link function updateActiveNav() { // Get current scroll position (add offset to account for nav height) const scrollPosition = window.scrollY + 80; // Loop through each section to find which one is in view sections.forEach(section => { const sectionTop = section.offsetTop; const sectionHeight = section.offsetHeight; const sectionId = section.getAttribute('id'); // Check if scroll position is within the current section if (scrollPosition >= sectionTop && scrollPosition < sectionTop + sectionHeight) { // Remove active class from all links first navLinks.forEach(link => link.classList.remove('active')); // Add active class to the matching nav link document.querySelector(`.nav-link[href="#${sectionId}"]`).classList.add('active'); } }); } // Run once on page load to set initial active link updateActiveNav(); // Run on every scroll event window.addEventListener('scroll', updateActiveNav);
Bonus: Custom Smooth Scroll (Optional)
If you need more control over scrolling behavior (like centering sections), you can override the native scroll-behavior with JavaScript. Add this to your script:
// Add smooth scroll on nav link click navLinks.forEach(link => { link.addEventListener('click', (e) => { e.preventDefault(); // Prevent default anchor jump const targetSection = document.querySelector(link.getAttribute('href')); // Scroll to target section with custom behavior targetSection.scrollIntoView({ behavior: 'smooth', block: 'start' // Aligns section top to viewport top; use 'center' for centering }); }); });
How It Works
- The fixed nav stays at the top of the page as users scroll.
- Native
scroll-behavior: smoothhandles the smooth scrolling between sections. - The JavaScript scroll listener checks which section is currently visible and updates the active nav link’s styling.
- The offset in
scrollPositionensures the active link switches at the right time (adjust the80value to match your nav’s height).
This solution is lightweight, fully native, and avoids any jQuery dependencies—perfect for your learning journey with JavaScript!
内容的提问来源于stack exchange,提问作者MoeLester




