“MediaWiki:Common.js”的版本间的差异
来自部落与弯刀Wiki
Skyswordkill(讨论 | 贡献) |
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 hash = link.getAttribute("href").slice(1); |
| − | const | + | const target = document.getElementById(hash) || document.querySelector(`[id="${CSS.escape(hash)}"]`); |
| − | + | return target ? { link, target } : null; | |
| − | |||
| − | |||
| − | |||
}).filter(Boolean); | }).filter(Boolean); | ||
function updateHighlight() { | function updateHighlight() { | ||
| − | const | + | const scrollY = window.scrollY + 120; |
| + | let current = null; | ||
| − | + | for (let section of sections) { | |
| − | for ( | + | if (section.target.offsetTop <= scrollY) { |
| − | if (section.target.offsetTop <= | ||
current = section; | current = section; | ||
} else { | } else { | ||
| 第23行: | 第20行: | ||
} | } | ||
| − | + | tocLinks.forEach(l => l.classList.remove("active-section")); | |
| − | tocLinks.forEach( | + | if (current) current.link.classList.add("active-section"); |
| − | |||
| − | |||
| − | if (current) | ||
| − | |||
| − | |||
} | } | ||
| − | |||
updateHighlight(); | updateHighlight(); | ||
window.addEventListener("scroll", updateHighlight); | window.addEventListener("scroll", updateHighlight); | ||
}); | }); | ||
2025年6月10日 (二) 18:26的版本
/* 这里的任何JavaScript将为所有用户在每次页面载入时加载。 */
document.addEventListener("DOMContentLoaded", function () {
const tocLinks = Array.from(document.querySelectorAll("#toc a"));
const sections = tocLinks.map(link => {
const hash = link.getAttribute("href").slice(1);
const target = document.getElementById(hash) || document.querySelector(`[id="${CSS.escape(hash)}"]`);
return target ? { link, target } : null;
}).filter(Boolean);
function updateHighlight() {
const scrollY = window.scrollY + 120;
let current = null;
for (let section of sections) {
if (section.target.offsetTop <= scrollY) {
current = section;
} else {
break;
}
}
tocLinks.forEach(l => l.classList.remove("active-section"));
if (current) current.link.classList.add("active-section");
}
updateHighlight();
window.addEventListener("scroll", updateHighlight);
});