main.ts 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. document.addEventListener('DOMContentLoaded', () => {
  2. const topBar = document.querySelector('.top-bar');
  3. if (topBar) {
  4. window.addEventListener('scroll', (e) => {
  5. if (window.scrollY === 0) {
  6. topBar.classList.remove('floating');
  7. } else {
  8. topBar.classList.add('floating');
  9. }
  10. });
  11. }
  12. highlightToc();
  13. }, false);
  14. /**
  15. * Highlight the current section in the table of contents when scrolling.
  16. */
  17. function highlightToc() {
  18. const toc = document.querySelector('#TableOfContents') as HTMLElement;
  19. const article = document.querySelector('article');
  20. if (toc && article) {
  21. const headers: HTMLHeadingElement[] = Array.from(article.querySelectorAll('h1[id],h2[id],h3[id]'));
  22. window.addEventListener('scroll', (e) => {
  23. highlightCurrentSection(headers);
  24. });
  25. highlightCurrentSection(headers);
  26. }
  27. function highlightCurrentSection(headers: HTMLElement[]) {
  28. const locationHash = location.hash;
  29. Array.from(toc.querySelectorAll('.active')).forEach(el => el.classList.remove('active'));
  30. // tslint:disable:prefer-for-of
  31. for (let i = 0; i < headers.length; i++) {
  32. const header = headers[i];
  33. const nextHeader = headers[i + 1];
  34. const id = header.getAttribute('id') as string;
  35. if (!nextHeader || (nextHeader && (window.scrollY + window.innerHeight - 200) < nextHeader.offsetTop)) {
  36. highlightItem(id);
  37. return;
  38. }
  39. const isCurrentTarget = `#${id}` === locationHash;
  40. const currentTargetOffset = isCurrentTarget ? 90 : 0;
  41. if ((header.offsetTop + currentTargetOffset) >= window.scrollY) {
  42. highlightItem(id);
  43. return;
  44. }
  45. }
  46. }
  47. function highlightItem(id: string) {
  48. const tocItem = toc.querySelector(`[href="#${id}"]`);
  49. if (tocItem) {
  50. tocItem.classList.add('active');
  51. }
  52. }
  53. }