|
| 1 | +document.addEventListener("DOMContentLoaded", function() { |
| 2 | + const toc = document.getElementById("toc"); |
| 3 | + const headers = document.querySelectorAll("#content h1, #content h2, #content h3, #content h4, #content h5, #content h6"); |
| 4 | + |
| 5 | + headers.forEach(header => { |
| 6 | + const li = document.createElement("li"); |
| 7 | + li.textContent = header.textContent; |
| 8 | + li.dataset.target = header.id || header.textContent.replace(/\s+/g, '-').toLowerCase(); |
| 9 | + header.id = li.dataset.target; |
| 10 | + |
| 11 | + li.addEventListener("click", function() { |
| 12 | + document.getElementById(header.id).scrollIntoView({ behavior: "smooth" }); |
| 13 | + }); |
| 14 | + |
| 15 | + const level = parseInt(header.tagName.charAt(1), 10); |
| 16 | + if (level === 1) { |
| 17 | + toc.appendChild(li); |
| 18 | + } else { |
| 19 | + let parentLi = toc.querySelector(`li[data-target="${header.parentElement.id}"]`); |
| 20 | + if (parentLi) { |
| 21 | + let ul = parentLi.querySelector("ul"); |
| 22 | + if (!ul) { |
| 23 | + ul = document.createElement("ul"); |
| 24 | + parentLi.appendChild(ul); |
| 25 | + } |
| 26 | + ul.appendChild(li); |
| 27 | + } |
| 28 | + } |
| 29 | + }); |
| 30 | + |
| 31 | + const options = { |
| 32 | + root: null, |
| 33 | + threshold: 0.5, |
| 34 | + }; |
| 35 | + |
| 36 | + const callback = (entries) => { |
| 37 | + entries.forEach(entry => { |
| 38 | + const id = entry.target.id; |
| 39 | + const li = toc.querySelector(`li[data-target="${id}"]`); |
| 40 | + if (entry.isIntersecting) { |
| 41 | + if (li) { |
| 42 | + li.classList.add("active"); |
| 43 | + } |
| 44 | + } else { |
| 45 | + if (li) { |
| 46 | + li.classList.remove("active"); |
| 47 | + } |
| 48 | + } |
| 49 | + }); |
| 50 | + }; |
| 51 | + |
| 52 | + const observer = new IntersectionObserver(callback, options); |
| 53 | + headers.forEach(header => observer.observe(header)); |
| 54 | +}); |
0 commit comments