document.addEventListener('DOMContentLoaded', function () { const sections = document.querySelectorAll('.section'); const navLinks = document.querySelectorAll('.nav-link'); const menuToggle = document.querySelector('.menu-toggle'); const navMenu = document.querySelector('.nav-menu'); const sectionContainer = document.querySelector('.section-container'); // 汉堡菜单点击事件 menuToggle.addEventListener('click', function () { this.classList.toggle('active'); navMenu.classList.toggle('active'); }); // 导航链接点击事件 navLinks.forEach(link => { link.addEventListener('click', function (e) { e.preventDefault(); const targetId = this.getAttribute('href'); const targetSection = document.querySelector(targetId); // 关闭移动端菜单 menuToggle.classList.remove('active'); navMenu.classList.remove('active'); // 滚动到对应模块 targetSection.scrollIntoView({ behavior: 'smooth' }); }); }); // 模块化滚动检测 sectionContainer.addEventListener('scroll', function () { const currentScroll = this.scrollTop; const windowHeight = window.innerHeight; sections.forEach((section, index) => { const sectionTop = index * windowHeight; const sectionBottom = (index + 1) * windowHeight; if (currentScroll >= sectionTop && currentScroll < sectionBottom) { const currentId = section.getAttribute('id'); navLinks.forEach(link => { link.classList.remove('active'); if (link.getAttribute('href') === `#${currentId}`) { link.classList.add('active'); } }); } }); }); // 阻止默认滚动行为 window.addEventListener('wheel', function (e) { if (e.cancelable) { e.preventDefault(); } const delta = Math.sign(e.deltaY); const currentIndex = Math.round(sectionContainer.scrollTop / window.innerHeight); const maxIndex = sections.length - 1; let targetIndex = currentIndex + delta; targetIndex = Math.max(0, Math.min(targetIndex, maxIndex)); sectionContainer.scrollTo({ top: targetIndex * window.innerHeight, behavior: 'smooth' }); }, { passive: false }); // 触摸设备支持 let startY; sectionContainer.addEventListener('touchstart', function (e) { startY = e.touches[0].clientY; }, { passive: true }); sectionContainer.addEventListener('touchmove', function (e) { if (e.cancelable) { e.preventDefault(); } const currentY = e.touches[0].clientY; const deltaY = startY - currentY; if (Math.abs(deltaY) > 50) { // 滑动阈值 const direction = deltaY > 0 ? 1 : -1; const currentIndex = Math.round(sectionContainer.scrollTop / window.innerHeight); const maxIndex = sections.length - 1; let targetIndex = currentIndex + direction; targetIndex = Math.max(0, Math.min(targetIndex, maxIndex)); sectionContainer.scrollTo({ top: targetIndex * window.innerHeight, behavior: 'smooth' }); startY = currentY; } }, { passive: false }); // 初始化高亮 sectionContainer.dispatchEvent(new Event('scroll')); });