document.addEventListener('DOMContentLoaded', () => { // --- 交互功能1: 响应式汉堡菜单 --- const hamburgerMenu = document.getElementById('hamburger-menu'); const mainNav = document.querySelector('.main-nav'); if (hamburgerMenu && mainNav) { hamburgerMenu.addEventListener('click', () => { mainNav.classList.toggle('active'); }); } // --- 交互功能2 (进阶): 白天/黑夜模式切换 --- const themeSwitcher = document.getElementById('theme-switcher'); const body = document.body; const currentTheme = localStorage.getItem('theme'); if (currentTheme === 'dark') { body.classList.add('dark-mode'); if (themeSwitcher) themeSwitcher.textContent = '🌙'; } else { if (themeSwitcher) themeSwitcher.textContent = '☀️'; } if (themeSwitcher) { themeSwitcher.addEventListener('click', () => { body.classList.toggle('dark-mode'); if (body.classList.contains('dark-mode')) { localStorage.setItem('theme', 'dark'); themeSwitcher.textContent = '🌙'; } else { localStorage.setItem('theme', 'light'); themeSwitcher.textContent = '☀️'; } }); } // --- 交互功能3 (进阶): 联系表单异步提交 (配合PHP) --- const contactForm = document.getElementById('contact-form'); if (contactForm) { contactForm.addEventListener('submit', function(event) { event.preventDefault(); let statusDiv = this.querySelector('.form-status'); if (!statusDiv) { statusDiv = document.createElement('div'); statusDiv.className = 'form-status'; this.appendChild(statusDiv); } const formData = new FormData(this); fetch('handle_contact.php', { method: 'POST', body: formData }) .then(response => response.text().then(text => ({ ok: response.ok, text }))) .then(({ ok, text }) => { statusDiv.textContent = text; statusDiv.style.color = ok ? 'green' : 'red'; if (ok) contactForm.reset(); }) .catch(error => { statusDiv.textContent = '提交失败,请检查网络连接。'; statusDiv.style.color = 'red'; }); }); } // --- 交互功能4 (进阶): 自动播放轮播图 --- const carousel = document.querySelector('.carousel'); if (carousel) { const items = carousel.querySelectorAll('.carousel-item'); const prevBtn = carousel.querySelector('.carousel-control.prev'); const nextBtn = carousel.querySelector('.carousel-control.next'); let currentIndex = 0; let intervalId = null; if (items.length > 1) { const showItem = (index) => items.forEach((item, i) => item.classList.toggle('active', i === index)); const nextItem = () => { currentIndex = (currentIndex + 1) % items.length; showItem(currentIndex); }; const prevItem = () => { currentIndex = (currentIndex - 1 + items.length) % items.length; showItem(currentIndex); }; const startCarousel = () => { stopCarousel(); intervalId = setInterval(nextItem, 3000); }; const stopCarousel = () => clearInterval(intervalId); if (nextBtn) nextBtn.addEventListener('click', () => { nextItem(); startCarousel(); }); if (prevBtn) prevBtn.addEventListener('click', () => { prevItem(); startCarousel(); }); carousel.addEventListener('mouseenter', stopCarousel); carousel.addEventListener('mouseleave', startCarousel); showItem(currentIndex); startCarousel(); } } });