Node.js API目录优化

将Node.js API 目录改为可伸缩的侧边栏,另添加滚动监听。

  1. // ==UserScript==
  2. // @name Node.js API目录优化
  3. // @namespace http://tampermonkey.net/
  4. // @version 1.0
  5. // @description 将Node.js API 目录改为可伸缩的侧边栏,另添加滚动监听。
  6. // @author zy
  7. // @include http://nodejs.cn/api/*
  8. // @include https://nodejs.org/api/*
  9. // @grant none
  10. // ==/UserScript==
  11.  
  12. (function() {
  13. 'use strict';
  14. var head = document.querySelector('head');
  15. var toc = document.querySelector('#toc');
  16. var style = document.createElement('style');
  17. var arrow = document.createElement('div');
  18. var mark = document.querySelectorAll('a[class="mark"]');
  19. var aLabel = document.querySelectorAll('#toc a');
  20. var dirCoord = {};
  21. var tArr = [];
  22. var idArr = [];
  23. style.innerText = ` #toc{ height: ${innerHeight}px; overflow: auto; position: fixed; top: 0; right: 0; z-index: 10; background: #fff; border-left: 2px solid #333333; transition:right 0.4s;} a.active{ color: #FFF; background-color: #43853d;}`;
  24. arrow.id = 'arrow';
  25. toc.append(arrow);
  26. document.head.appendChild(style);
  27. style.innerText += ` #arrow{ opacity: 0.8; position: fixed; top: calc(50% - 25px); right: ${toc.offsetWidth}px; background: #333; z-index: 11; color: #fff; border-top: 25px solid #333; border-bottom: 25px solid #333; border-left: 20px solid #43853d; cursor:pointer; transition:right 0.4s;} .hide-toc{ right: -${toc.offsetWidth}px !important; } .hide-arrow{ right: 0px !important; border-left: none !important; border-right: 25px solid #43853d;}`;
  28. mark.forEach((item)=>{
  29. dirCoord[item.id] = item.parentNode.parentNode.offsetTop;
  30. idArr.push(item.id);
  31. });
  32. arrow.onclick = ()=>{
  33. if(toc.className === 'hide-toc'){
  34. toc.className = '';
  35. arrow.className = '';
  36. }
  37. else{
  38. toc.className = 'hide-toc';
  39. arrow.className = 'hide-arrow';
  40. }
  41. };
  42. window.onscroll = () =>{
  43. tArr = [];
  44. for(let i in dirCoord){
  45. tArr.push(dirCoord[i]);
  46. if(dirCoord[i] > pageYOffset){
  47. tArr.pop();
  48. let _max = Math.max.apply(Math,tArr);
  49. let _index = tArr.indexOf(_max);
  50. let _id = idArr[_index];
  51. aLabel.forEach((item)=>{
  52. item.className = '';
  53. });
  54. document.querySelector('[href="#'+ _id +'"]').className = 'active';
  55. break;
  56. }
  57. }
  58. };
  59. })();