|
| 1 | + |
| 2 | + document.addEventListener('DOMContentLoaded', function () { |
| 3 | + const navLinks = document.querySelectorAll('.navbar-nav .nav-link'); |
| 4 | + const sections = Array.from(navLinks) |
| 5 | + .map(link => document.querySelector(link.getAttribute('href'))) |
| 6 | + .filter(Boolean); |
| 7 | + |
| 8 | + const activateLink = (link) => { |
| 9 | + navLinks.forEach(item => { |
| 10 | + item.classList.remove('text-primary'); |
| 11 | + item.classList.add('text-dark'); |
| 12 | + }); |
| 13 | + if (link) { |
| 14 | + link.classList.add('text-primary'); |
| 15 | + link.classList.remove('text-dark'); |
| 16 | + } |
| 17 | + }; |
| 18 | + |
| 19 | + navLinks.forEach(link => { |
| 20 | + link.addEventListener('mouseenter', () => { |
| 21 | + activateLink(link); |
| 22 | + }); |
| 23 | + link.addEventListener('mouseleave', () => { |
| 24 | + const activeLink = document.querySelector('.navbar-nav .nav-link.active'); |
| 25 | + activateLink(activeLink); |
| 26 | + }); |
| 27 | + link.addEventListener('click', (event) => { |
| 28 | + navLinks.forEach(item => item.classList.remove('active')); |
| 29 | + link.classList.add('active'); |
| 30 | + activateLink(link); |
| 31 | + }); |
| 32 | + }); |
| 33 | + |
| 34 | + const onScroll = () => { |
| 35 | + const scrollPosition = window.scrollY + window.innerHeight / 3; |
| 36 | + let currentSection = null; |
| 37 | + |
| 38 | + sections.forEach(section => { |
| 39 | + if (section.offsetTop <= scrollPosition && section.offsetTop + section.offsetHeight > scrollPosition) { |
| 40 | + currentSection = section; |
| 41 | + } |
| 42 | + }); |
| 43 | + |
| 44 | + if (currentSection) { |
| 45 | + const newActive = document.querySelector(`.navbar-nav .nav-link[href="#${currentSection.id}"]`); |
| 46 | + if (newActive) { |
| 47 | + navLinks.forEach(item => item.classList.remove('active')); |
| 48 | + newActive.classList.add('active'); |
| 49 | + activateLink(newActive); |
| 50 | + } |
| 51 | + } |
| 52 | + }; |
| 53 | + |
| 54 | + window.addEventListener('scroll', onScroll); |
| 55 | + onScroll(); |
| 56 | + }); |
0 commit comments