博客园编辑页面添加目录跳转

博客园编辑页面左上角添加指向所有h1标题的跳转链接目录,以免文章太长滚动麻烦

  1. // ==UserScript==
  2. // @name 博客园编辑页面添加目录跳转
  3. // @description 博客园编辑页面左上角添加指向所有h1标题的跳转链接目录,以免文章太长滚动麻烦
  4. // @include https://i.cnblogs.com/posts/edit*
  5. // @version 2024-03-14
  6. /************************************/
  7. // @icon https://www.google.com/s2/favicons?sz=64&domain=cnblogs.com
  8. // @grant GM_addStyle
  9. // @license LGPLv3
  10. // @namespace https://greasyfork.org/users/1097076
  11. // ==/UserScript==
  12.  
  13. var nodeRemove;
  14.  
  15. function createTableOfContents() {
  16. if (nodeRemove) {
  17. nodeRemove.remove();
  18. }
  19.  
  20. // let contentsDiv = document.createElement("div");
  21. nodeRemove = document.createElement("div");
  22. // contentsDiv.className = "contentsDiv";
  23. nodeRemove.classList.add("contentsDiv");
  24.  
  25.  
  26. // let tocItems = [];
  27. let h1list // h1list is not defined 需要放外边
  28. try {
  29. h1list = document.querySelector("#Editor_Edit_EditorBody_ifr").contentWindow.document.querySelectorAll("#tinymce > h1")
  30. } catch (e) {
  31. h1list = document.querySelector("#postBodyEditor_ifr").contentWindow.document.querySelectorAll("#tinymce h1") // TinyMCE5
  32. }
  33.  
  34.  
  35. h1list.forEach(element => {
  36. let tocItem = document.createElement('a');
  37. tocItem.style.display = 'block';
  38. tocItem.textContent = element.innerText;
  39. nodeRemove.appendChild(tocItem)
  40.  
  41. // Add a click event listener to each tocItem
  42. tocItem.addEventListener('click', function () {
  43. // Scroll to the corresponding h1 element
  44. element.scrollIntoView({
  45. behavior: 'smooth', // Add smooth scrolling effect
  46. block: 'start', // Align the top of the element with the top of the viewport
  47. });
  48. });
  49. }); // 目录
  50.  
  51. document.body.appendChild(nodeRemove)
  52.  
  53. const styleText = `
  54. .contentsDiv {
  55. position: fixed;
  56. top: 0;
  57. left: 0;
  58. }
  59.  
  60. .tooltiptext:hover {
  61. display: inline;
  62. }
  63. `
  64. const style = GM_addStyle(styleText); // 点击Styles .cls右边的+号,点击inspector-stylesheet来粘贴调试
  65.  
  66. }
  67.  
  68. setTimeout(createTableOfContents, 3000);
  69. setInterval(createTableOfContents, 10000);