优化web逻辑

This commit is contained in:
Alex Yang
2025-11-27 18:51:47 +08:00
parent 65ff630868
commit 46acf4123a

View File

@@ -2617,34 +2617,100 @@ function showNotification(message, type = 'info') {
function handlePageSwitch() {
const menuItems = document.querySelectorAll('nav a');
menuItems.forEach(item => {
item.addEventListener('click', (e) => {
e.preventDefault();
const targetId = item.getAttribute('href').substring(1);
// 页面切换逻辑
function switchPage(targetId, menuItem) {
// 隐藏所有内容
document.querySelectorAll('[id$="-content"]').forEach(content => {
content.classList.add('hidden');
});
// 隐藏所有内容
document.querySelectorAll('[id$="-content"]').forEach(content => {
content.classList.add('hidden');
});
// 显示目标内容
document.getElementById(`${targetId}-content`).classList.remove('hidden');
// 显示目标内容
document.getElementById(`${targetId}-content`).classList.remove('hidden');
// 更新页面标题
document.getElementById('page-title').textContent = menuItem.querySelector('span').textContent;
// 更新页面标题
document.getElementById('page-title').textContent = item.querySelector('span').textContent;
// 更新活动菜单项
menuItems.forEach(item => {
item.classList.remove('sidebar-item-active');
});
menuItem.classList.add('sidebar-item-active');
// 更新活动菜单项
menuItems.forEach(menuItem => {
menuItem.classList.remove('sidebar-item-active');
});
item.classList.add('sidebar-item-active');
// 侧边栏切换(移动端)
if (window.innerWidth < 1024) {
toggleSidebar();
}
}
// 侧边栏切换(移动端)
if (window.innerWidth < 1024) {
toggleSidebar();
// 处理hash变化
function handleHashChange() {
let hash = window.location.hash;
// 如果没有hash默认设置为#dashboard
if (!hash) {
hash = '#dashboard';
window.location.hash = hash;
return;
}
const targetId = hash.substring(1);
// 查找对应的菜单项
let targetMenuItem = null;
menuItems.forEach(item => {
if (item.getAttribute('href') === hash) {
targetMenuItem = item;
}
});
// 如果找到了对应的菜单项,切换页面
if (targetMenuItem) {
switchPage(targetId, targetMenuItem);
} else {
// 如果没有找到对应的菜单项,尝试显示对应的内容
const contentElement = document.getElementById(`${targetId}-content`);
if (contentElement) {
// 隐藏所有内容
document.querySelectorAll('[id$="-content"]').forEach(content => {
content.classList.add('hidden');
});
// 显示目标内容
contentElement.classList.remove('hidden');
// 查找对应的菜单项并更新活动状态
menuItems.forEach(item => {
item.classList.remove('sidebar-item-active');
if (item.getAttribute('href') === hash) {
item.classList.add('sidebar-item-active');
// 更新页面标题
document.getElementById('page-title').textContent = item.querySelector('span').textContent;
}
});
} else {
// 如果没有找到对应的内容默认显示dashboard
window.location.hash = '#dashboard';
}
}
}
// 初始化hash路由
function initHashRoute() {
handleHashChange();
}
// 监听hash变化事件
window.addEventListener('hashchange', handleHashChange);
menuItems.forEach(item => {
item.addEventListener('click', (e) => {
// 允许默认的hash变化
// 页面切换会由hashchange事件处理
});
});
// 初始化hash路由
initHashRoute();
}
// 侧边栏切换