Generate markdown files' table of contents or anchor links menu automatically

Generate markdown files' table of contents or anchor links menu automatically, make markdown files easy to read

  1. // ==UserScript==
  2. // @name Generate markdown files' table of contents or anchor links menu automatically
  3. // @namespace http://tampermonkey.net/
  4. // @version 0.5
  5. // @description Generate markdown files' table of contents or anchor links menu automatically, make markdown files easy to read
  6. // @author ladyrank
  7. // @include https://github.com/*
  8. // @include https://*.muc*.cn/*
  9. // @include https://*.zuim*.com/*
  10. // @grant none
  11. // @require https://cdn.staticfile.org/jquery/3.4.1/jquery.min.js
  12. // ==/UserScript==
  13.  
  14. (function () {
  15. 'use strict';
  16.  
  17. var detect = function (){
  18. var links = $('a.anchor');
  19. var html = '';
  20. var $wrap = '';
  21. var winH = window.screen.availHeight || window.screen.height;
  22. if (!links || !links.length) {
  23. return false;
  24. }
  25. html = '<div id="wx-mkd-toc" style="z-index: 9999; position: fixed; bottom: 50px; right: 20px; background: #f2f2f2; padding: 10px; border: 1px solid #f2f2f2;"><h1 style="margin: 0; font-size: 16px;"><a href="javascript:;"><span>+</span>目录预览</a></h1><div class="wx-mkd-con" style="display: none; overflow: hidden; overflow-y: scroll; padding: 20px; max-height: '+ (winH*.5)+'px;"><ul style="margin: 0; padding: 0;">';
  26. $wrap = $('body');
  27. $.each(links, function (idx, item) {
  28. var $this = $(item);
  29. var $p = $this.parent();
  30. var tag = (($p[0] && $p[0].tagName) || '').toLowerCase();
  31. var tagNum = (tag || '').replace(/h/gi, '');
  32. var mLeft = tagNum * 10;
  33. html += '<li style="margin-left: ' + mLeft + 'px;" class="c_toc_' + tag + '"><a href="' + $this.attr('href') + '">' + $p.text() + '</a></li>'
  34. });
  35. html += '</ul></div></div>';
  36. $wrap.prepend(html);
  37.  
  38. $wrap.on('click', '#wx-mkd-toc h1', function(){
  39. var $this = $(this);
  40. var $thisSpan = $this.find('span');
  41. var thisSpanTxt = $thisSpan.text();
  42. var $thisCon = $this.parent().find('.wx-mkd-con');
  43. if(thisSpanTxt.match(/\+/gi)){
  44. $thisCon.show();
  45. $thisSpan.text('-');
  46. } else {
  47. $thisCon.hide();
  48. $thisSpan.text('+');
  49. }
  50. });
  51. };
  52.  
  53. setTimeout(function(){
  54. detect();
  55. }, 2000);
  56.  
  57. })();