“MediaWiki:Common.js”的版本间的差异
来自部落与弯刀Wiki
Skyswordkill(讨论 | 贡献) (创建页面,内容为“→这里的任何JavaScript将为所有用户在每次页面载入时加载。: document.addEventListener("DOMContentLoaded", function () { const tocLinks = A…”) |
Skyswordkill(讨论 | 贡献) |
||
| 第3行: | 第3行: | ||
const tocLinks = Array.from(document.querySelectorAll("#toc a")); | const tocLinks = Array.from(document.querySelectorAll("#toc a")); | ||
const sections = tocLinks.map(link => { | const sections = tocLinks.map(link => { | ||
| − | const | + | const id = decodeURIComponent(link.getAttribute("href").slice(1)); |
| − | return | + | const el = document.getElementById(id); |
| + | if (el) { | ||
| + | return { link: link, target: el }; | ||
| + | } | ||
| + | return null; | ||
}).filter(Boolean); | }).filter(Boolean); | ||
| − | function | + | function updateHighlight() { |
| − | + | const scrollPosition = window.scrollY + 120; | |
| − | const | ||
| − | + | let current = null; | |
| − | + | for (const section of sections) { | |
| − | + | if (section.target.offsetTop <= scrollPosition) { | |
| − | + | current = section; | |
} else { | } else { | ||
break; | break; | ||
| 第20行: | 第23行: | ||
} | } | ||
| + | // 清除所有高亮 | ||
tocLinks.forEach(link => link.classList.remove("active-section")); | tocLinks.forEach(link => link.classList.remove("active-section")); | ||
| − | if ( | + | |
| − | + | // 添加当前高亮 | |
| + | if (current) { | ||
| + | current.link.classList.add("active-section"); | ||
} | } | ||
} | } | ||
| − | window.addEventListener("scroll", | + | // 首次触发 + 滚动触发 |
| − | + | updateHighlight(); | |
| + | window.addEventListener("scroll", updateHighlight); | ||
}); | }); | ||
2025年6月10日 (二) 18:25的版本
/* 这里的任何JavaScript将为所有用户在每次页面载入时加载。 */
document.addEventListener("DOMContentLoaded", function () {
const tocLinks = Array.from(document.querySelectorAll("#toc a"));
const sections = tocLinks.map(link => {
const id = decodeURIComponent(link.getAttribute("href").slice(1));
const el = document.getElementById(id);
if (el) {
return { link: link, target: el };
}
return null;
}).filter(Boolean);
function updateHighlight() {
const scrollPosition = window.scrollY + 120;
let current = null;
for (const section of sections) {
if (section.target.offsetTop <= scrollPosition) {
current = section;
} else {
break;
}
}
// 清除所有高亮
tocLinks.forEach(link => link.classList.remove("active-section"));
// 添加当前高亮
if (current) {
current.link.classList.add("active-section");
}
}
// 首次触发 + 滚动触发
updateHighlight();
window.addEventListener("scroll", updateHighlight);
});