/** * 通用导航管理脚本 * 用于处理页面间导航和活动状态 */ class NavigationManager { constructor() { this.currentPage = this.getCurrentPage(); this.init(); } init() { // 设置当前页面的活动状态 this.setActiveNavigation(); // 添加导航点击事件监听 this.addNavigationListeners(); // 添加页面加载完成后的处理 this.addPageLoadHandlers(); } getCurrentPage() { const path = window.location.pathname; if (path === '/' || path === '/dashboard') return 'dashboard'; if (path === '/alerts') return 'alerts'; if (path === '/chat') return 'chat'; if (path === '/chat-http') return 'chat-http'; return 'dashboard'; } setActiveNavigation() { // 清除所有活动状态 document.querySelectorAll('.nav-link').forEach(link => { link.classList.remove('active'); }); // 设置当前页面的活动状态 const activeSelectors = { 'dashboard': 'a.nav-link[href="/dashboard"]', 'alerts': 'a.nav-link[href="/alerts"]', 'chat': 'a.nav-link[href="/chat"]', 'chat-http': 'a.nav-link[href="/chat-http"]' }; const selector = activeSelectors[this.currentPage]; if (selector) { document.querySelectorAll(selector).forEach(link => { link.classList.add('active'); }); } } addNavigationListeners() { // 对导航链接添加点击处理 document.querySelectorAll('a.nav-link[href^="/"]').forEach(link => { link.addEventListener('click', (e) => { const href = link.getAttribute('href'); // 如果是当前页面,阻止默认行为 if (href === window.location.pathname) { e.preventDefault(); return; } // 显示加载状态 this.showLoadingState(); // 正常跳转 // 注意:这里不阻止默认行为,让浏览器正常跳转 }); }); // 对 dashboard.html 的侧边栏导航特殊处理 document.querySelectorAll('.sidebar a.nav-link[href^="/"]').forEach(link => { link.addEventListener('click', (e) => { this.showLoadingState(); }); }); } showLoadingState() { // 显示加载提示 const loadingHtml = ` `; document.body.insertAdjacentHTML('beforeend', loadingHtml); } addPageLoadHandlers() { // 页面加载完成后移除加载状态 window.addEventListener('load', () => { const loading = document.getElementById('navigation-loading'); if (loading) { loading.remove(); } }); // 处理浏览器前进后退 window.addEventListener('popstate', () => { this.currentPage = this.getCurrentPage(); this.setActiveNavigation(); }); } // 手动导航到指定页面 navigateTo(page) { const urls = { 'dashboard': '/dashboard', 'alerts': '/alerts', 'chat': '/chat', 'chat-http': '/chat-http' }; const url = urls[page]; if (url && url !== window.location.pathname) { this.showLoadingState(); window.location.href = url; } } } // 页面加载完成后初始化导航管理器 document.addEventListener('DOMContentLoaded', () => { window.navigationManager = new NavigationManager(); }); // 导航函数,可以在控制台或页面中使用 window.navigateTo = (page) => { if (window.navigationManager) { window.navigationManager.navigateTo(page); } };