document.addEventListener('DOMContentLoaded', function() { const navToggle = document.getElementById('navToggle'); const navMenu = document.getElementById('navMenu'); const body = document.body; const goTopBtn = document.getElementById('goTop'); // 汉堡菜单切换 if (navToggle && navMenu) { navToggle.addEventListener('click', function(e) { e.stopPropagation(); this.classList.toggle('active'); navMenu.classList.toggle('active'); body.classList.toggle('nav-open'); }); // 点击菜单项自动关闭 navMenu.querySelectorAll('a').forEach(link => { link.addEventListener('click', () => { if (window.innerWidth <= 768) { navToggle.classList.remove('active'); navMenu.classList.remove('active'); body.classList.remove('nav-open'); } }); }); // 点击外部区域关闭菜单 document.addEventListener('click', function(e) { if (navMenu.classList.contains('active') && !navToggle.contains(e.target) && !navMenu.contains(e.target)) { navToggle.classList.remove('active'); navMenu.classList.remove('active'); body.classList.remove('nav-open'); } }); } // 返回顶部按钮 if (goTopBtn) { window.addEventListener('scroll', () => { goTopBtn.style.display = (window.scrollY > 300) ? 'block' : 'none'; }); goTopBtn.addEventListener('click', () => { window.scrollTo({ top: 0, behavior: 'smooth' }); }); } // 导航栏滚动阴影 const header = document.querySelector('.main-header'); if (header) { window.addEventListener('scroll', () => { header.classList.toggle('scrolled', window.scrollY > 10); }); } // 表单验证增强(移动端友好) const phoneInputs = document.querySelectorAll('input[type="tel"]'); phoneInputs.forEach(input => { input.addEventListener('input', function() { this.value = this.value.replace(/[^\d]/g, ''); if (this.value.length > 11) { this.value = this.value.slice(0, 11); } }); }); // 图片懒加载(原生支持) if ('loading' in HTMLImageElement.prototype) { const images = document.querySelectorAll('img[loading="lazy"]'); images.forEach(img => { img.setAttribute('src', img.dataset.src || img.getAttribute('src')); }); } else { // 降级处理:立即加载 document.querySelectorAll('img[loading="lazy"]').forEach(img => { img.removeAttribute('loading'); }); } // 防止iOS Safari橡皮筋效果(可选) if (/iPhone|iPad|iPod/.test(navigator.userAgent)) { let startY = 0; document.body.addEventListener('touchstart', function(e) { startY = e.touches[0].clientY; }); document.body.addEventListener('touchmove', function(e) { const scrollTop = document.documentElement.scrollTop || document.body.scrollTop; if ((scrollTop === 0 && e.touches[0].clientY > startY) || (scrollTop === document.body.scrollHeight - window.innerHeight && e.touches[0].clientY < startY)) { e.preventDefault(); } }); } });