// Modern Template JavaScript (function() { 'use strict'; // 页面加载完成后执行 document.addEventListener('DOMContentLoaded', function() { // 导航栏滚动效果 const nav = document.querySelector('.nav'); if (nav) { window.addEventListener('scroll', function() { if (window.scrollY > 50) { nav.style.background = 'rgba(255, 255, 255, 0.95)'; nav.style.backdropFilter = 'blur(10px)'; } else { nav.style.background = '#fff'; nav.style.backdropFilter = 'none'; } }); } // 平滑滚动 const links = document.querySelectorAll('a[href^="#"]'); links.forEach(link => { link.addEventListener('click', function(e) { e.preventDefault(); const target = document.querySelector(this.getAttribute('href')); if (target) { target.scrollIntoView({ behavior: 'smooth', block: 'start' }); } }); }); // 图片懒加载 const images = document.querySelectorAll('img[data-src]'); if (images.length > 0 && 'IntersectionObserver' in window) { const imageObserver = new IntersectionObserver((entries, observer) => { entries.forEach(entry => { if (entry.isIntersecting) { const img = entry.target; img.src = img.dataset.src; img.removeAttribute('data-src'); observer.unobserve(img); } }); }); images.forEach(img => imageObserver.observe(img)); } // 表单验证增强 const forms = document.querySelectorAll('form'); forms.forEach(form => { const inputs = form.querySelectorAll('input, textarea'); inputs.forEach(input => { input.addEventListener('blur', function() { validateField(this); }); }); }); function validateField(field) { const value = field.value.trim(); const type = field.type; const name = field.name; // 移除之前的错误样式 field.classList.remove('error'); // 基本验证 if (field.hasAttribute('required') && !value) { showFieldError(field, '此字段为必填项'); return false; } // 特定字段验证 if (name === 'email' && value) { const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; if (!emailRegex.test(value)) { showFieldError(field, '请输入有效的邮箱地址'); return false; } } if (name === 'phone' && value) { const phoneRegex = /^1[3-9]\d{9}$/; if (!phoneRegex.test(value)) { showFieldError(field, '请输入有效的手机号码'); return false; } } // 清除错误状态 clearFieldError(field); return true; } function showFieldError(field, message) { field.classList.add('error'); // 可以在这里添加错误消息显示逻辑 } function clearFieldError(field) { field.classList.remove('error'); // 可以在这里添加清除错误消息的逻辑 } }); // 工具函数 window.ModernTemplate = { // 显示消息 showMessage: function(message, type = 'info') { // 简单的消息显示,可以根据需要扩展 alert(message); }, // 格式化日期 formatDate: function(date) { if (typeof date === 'string') { date = new Date(date); } return date.toLocaleDateString('zh-CN'); }, // 截断文本 truncateText: function(text, length = 100) { if (text.length <= length) return text; return text.substring(0, length) + '...'; } }; })();