Files
labweb/public/js/module-loader.js
2025-12-16 11:39:15 +08:00

88 lines
3.6 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
document.addEventListener("DOMContentLoaded", function() {
// 加载 Header添加缓存控制确保获取最新版本
fetch('/public/components/header.html', {
cache: 'no-cache',
headers: {
'Cache-Control': 'no-cache'
}
})
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.text();
})
.then(data => {
const placeholder = document.getElementById('header-placeholder');
if (placeholder) {
placeholder.innerHTML = data;
// 确保所有链接都是绝对路径
const links = placeholder.querySelectorAll('a[href]');
links.forEach(link => {
const href = link.getAttribute('href');
if (href && !href.startsWith('/') && !href.startsWith('http') && !href.startsWith('#')) {
// 如果是相对路径,转换为绝对路径
if (href.startsWith('./')) {
link.setAttribute('href', href.replace('./', '/'));
} else if (!href.startsWith('/')) {
link.setAttribute('href', '/' + href);
}
}
});
setActiveLink(); // 头部加载完后设置高亮
}
})
.catch(error => console.error('Error loading header:', error));
// 加载 Footer
fetch('/public/components/footer.html', {
cache: 'no-cache',
headers: {
'Cache-Control': 'no-cache'
}
})
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.text();
})
.then(data => {
const placeholder = document.getElementById('footer-placeholder');
if (placeholder) {
placeholder.innerHTML = data;
}
})
.catch(error => console.error('Error loading footer:', error));
});
// 设置导航高亮
function setActiveLink() {
const currentPath = window.location.pathname;
const page = currentPath.split("/").pop() || "index.html"; // 如果是根路径默认为index.html
const links = document.querySelectorAll('.nev-child-1 > li > a');
links.forEach(link => {
// 优先使用 data-page 属性,如果没有则从 href 中提取文件名
let targetPage = link.getAttribute('data-page');
if (!targetPage) {
const href = link.getAttribute('href') || '';
// 处理绝对路径(如 /Browse.html和相对路径如 ./Browse.html
if (href.startsWith('/')) {
targetPage = href.split('/').pop();
} else {
targetPage = href.replace(/^\.\//, '').split('?')[0]; // 移除 ./ 前缀和查询参数
}
}
// 简单匹配:如果当前文件名包含目标链接名 (处理 Search.html 和 Search_merged.html 的情况)
// 或者完全相等
if (page === targetPage || (targetPage !== 'index.html' && page.includes(targetPage.split('.')[0]))) {
link.classList.add('active-link'); // 在layout.css中定义样式
// 同时设置原有行内样式的颜色(兼容旧逻辑)
link.style.color = "black";
}
});
}