Sticky Table of Contents - wikipedia.org

12/26/2021, 1:29:58 PM

  1. // ==UserScript==
  2. // @name Sticky Table of Contents - wikipedia.org
  3. // @namespace Violentmonkey Scripts
  4. // @match https://*.wikipedia.org/wiki/*
  5. // @grant none
  6. // @version 1.0
  7. // @license GPL-3.0-only
  8. // @author Sidem
  9. // @description 12/26/2021, 1:29:58 PM
  10. // ==/UserScript==
  11. window.addEventListener('load', function () {
  12. let toc = document.getElementById('toc');
  13. toc.style.position = 'fixed';
  14. toc.style.right = '0px';
  15. toc.style.top = '100px';
  16. toc.style.opacity = '0.8';
  17. toc.style.width = '18%';
  18. toc.style.maxHeight = '65%';
  19. toc.style.display = 'block';
  20. toc.style.overflowY = 'auto';
  21. toc.addEventListener('mouseleave', e => { toc.style.opacity = '0.8'; });
  22. toc.addEventListener('mouseenter', e => { toc.style.opacity = '1.0'; });
  23. toc.parentElement.classList.add('toclimit-3');
  24. toc.parentElement.classList.remove('toclimit-2');
  25. let content = document.getElementById('content');
  26. content.style.marginRight = '20%';
  27. content.style.marginLeft = '15%';
  28. let sections = toc.getElementsByTagName('a');
  29. let anchorSet = [];
  30. for (let link of sections) {
  31. let id = link.href.split('#')[1];
  32. link.parentElement.id = "anchor_"+id;
  33. let item = document.getElementById(id);
  34. let scrollOffset = item.offsetTop;
  35. link.parentElement.dataset.scroll = scrollOffset;
  36. if (item.parentElement.tagName == 'H1' || item.parentElement.tagName == 'H2' || item.parentElement.tagName == 'H3') {
  37. anchorSet.push({id:id, scroll: scrollOffset, item: item, anchor: link.parentElement});
  38. }
  39. }
  40. let setHighlightedSection = (current) => {
  41. for (let anchor of anchorSet) {
  42. if (current == anchor.id) {
  43. anchor.anchor.style.fontWeight = '1000';
  44. anchor.anchor.scrollIntoView({behavior: "smooth"});
  45. } else {
  46. anchor.anchor.style.fontWeight = '100';
  47. }
  48. }
  49. };
  50. let getScrollDistance = (itemScroll) => {
  51. return Math.abs(itemScroll - (window.scrollY-(window.outerHeight-window.innerHeight)));
  52. };
  53. let computeTimer = 0;
  54. window.addEventListener('scroll', (e) => {
  55. if(e.timeStamp-computeTimer > 100) {
  56. computeTimer = e.timeStamp;
  57. let closestItem = {id:'placeholder', scroll:999999999};
  58. let curDistance = getScrollDistance(closestItem.scroll);
  59. let itemDistance = 0;
  60. for (let link of anchorSet) {
  61. itemDistance = getScrollDistance(link.scroll)
  62. if(itemDistance < curDistance) {
  63. closestItem = link;
  64. curDistance = itemDistance;
  65. }
  66. }
  67. setHighlightedSection(closestItem.id);
  68. }
  69. });
  70. }, false);

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址